<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Authorization, Content-Type");

// Include the database configuration file
require_once 'config.php'; 

// Get the database connection
$conn = getDbConnection();

// Verify database connection
if (!$conn) {
    error_log("Database connection failed: " . mysqli_connect_error());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database connection failed"]);
    exit();
}

// Enable error reporting for debugging (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Invalid request method. Only POST is allowed."]);
    exit();
}

// Step 1: Validate the Authorization Header
$headers = apache_request_headers();
$authHeader = $headers['Authorization'] ?? null;

if (!$authHeader || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Authorization token is missing or invalid."]);
    exit();
}

$token = $matches[1];

// Step 2: Validate Token and Retrieve User Information
$stmt = $conn->prepare("SELECT user_id FROM users WHERE token = ?");
if (!$stmt) {
    error_log("Database error: " . $conn->error);
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database error while preparing query."]);
    exit();
}

$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Unauthorized: Invalid token."]);
    exit();
}

$userId = $user['user_id'];


// Step 3: Handle the File Upload
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "No file uploaded or an upload error occurred."]);
    exit();
}

$file = $_FILES['image'];

// Validate file size (limit: 10MB)
if ($file['size'] > 10 * 1024 * 1024) { // 10MB
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "File size exceeds 10MB limit."]);
    exit();
}

// Validate file type (only JPEG and PNG allowed)
$allowedTypes = ['image/jpeg', 'image/png'];
if (!in_array($file['type'], $allowedTypes)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Invalid file type. Only JPEG and PNG are allowed."]);
    exit();
}

// Step 4: Prepare the Upload Directory
$uploadDir = __DIR__ . "/../uploads/user_$userId/";

if (!is_dir($uploadDir)) {
    if (!mkdir($uploadDir, 0755, true)) {
        error_log("Failed to create directory: $uploadDir");
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Failed to create upload directory."]);
        exit();
    }
}

// Sanitize and generate a unique file name
$fileName = uniqid() . "_" . preg_replace('/[^a-zA-Z0-9._-]/', '_', $file['name']);
$filePath = $uploadDir . $fileName;

// Step 5: Move the File to the Upload Directory
if (!move_uploaded_file($file['tmp_name'], $filePath)) {
    error_log("Failed to move uploaded file: " . $file['tmp_name']);
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to move uploaded file."]);
    exit();
}

// Step 6: Save File Metadata to the Database
$description = htmlspecialchars($_POST['description'] ?? '', ENT_QUOTES, 'UTF-8'); // Optional description

$stmt = $conn->prepare("INSERT INTO images (user_id, file_name, description) VALUES (?, ?, ?)");
if (!$stmt) {
    error_log("Database error during insertion: " . $conn->error);
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database error while preparing insertion query."]);
    exit();
}

$stmt->bind_param("iss", $userId, $fileName, $description);
if (!$stmt->execute()) {
    error_log("Database insertion failed: " . $stmt->error);
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to save image details in database."]);
    exit();
}

// Return a success response
http_response_code(200);
echo json_encode([
    "status" => "success",
    "message" => "Image uploaded successfully.",
    "file_name" => $fileName,
    "file_path" => "/guardianapi/uploads/user_$userId/$fileName"
]);
?>

