<?php
header('Content-Type: application/json');

// Start output buffering to avoid unwanted output breaking JSON
ob_start();

require "conn.php"; // ensure $con = mysqli_connect(...)

$debug_log = __DIR__ . "/debug_log.txt";

try {
    // Collect POST data
    $invoice_no    = $_POST['invoice_no'] ?? '';
    $transfer_date = $_POST['transfer_date'] ?? '';
    $transfer_time = $_POST['transfer_time'] ?? '';

    if (!$invoice_no || !$transfer_date || !$transfer_time) {
        throw new Exception("Missing required fields.");
    }

    if (!isset($_FILES['receipt_file']) || $_FILES['receipt_file']['error'] != 0) {
        throw new Exception("No file uploaded or file upload error.");
    }

    $file_tmp  = $_FILES['receipt_file']['tmp_name'];
    $file_name = $_FILES['receipt_file']['name'];
    $ext       = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    $allowed_ext = ['jpg','jpeg','png','heic'];
    if (!in_array($ext, $allowed_ext)) {
        throw new Exception("Invalid file type. Only JPG, JPEG, PNG, HEIC allowed.");
    }

    // Ensure upload directory exists
    $upload_dir = __DIR__ . "/uploads/receipts/";
    if (!is_dir($upload_dir) && !mkdir($upload_dir, 0777, true)) {
        throw new Exception("Failed to create upload directory.");
    }

    $new_name  = $invoice_no . ".jpg"; // Always save as JPG
    $file_path = $upload_dir . $new_name;

    // Convert image to JPG if needed
    $image_saved = false;

    if ($ext === 'jpg' || $ext === 'jpeg') {
        if (!move_uploaded_file($file_tmp, $file_path)) {
            throw new Exception("Failed to move uploaded JPG file.");
        }
        $image_saved = true;

    } elseif ($ext === 'png') {
        $image = imagecreatefrompng($file_tmp);
        if (!$image || !imagejpeg($image, $file_path, 90)) {
            throw new Exception("Failed to convert PNG to JPG.");
        }
        imagedestroy($image);
        $image_saved = true;

    } elseif ($ext === 'heic') {
        if (class_exists('Imagick')) {
            $im = new Imagick($file_tmp);
            $im->setImageFormat('jpeg');
            $im->writeImage($file_path);
            $im->clear();
            $im->destroy();
            $image_saved = true;
        } else {
            throw new Exception("HEIC files not supported on this server (Imagick missing).");
        }
    }

    if (!$image_saved || !file_exists($file_path) || filesize($file_path) === 0) {
        throw new Exception("File upload failed or file is empty.");
    }

    // Update invoice record
    $stmt = $con->prepare("UPDATE invoice 
        SET payment_status = 'Processing', 
            order_status = 'Processing',
            receipt_file = ?, 
            transfer_date = ?, 
            transfer_time = ?
        WHERE invoice_no = ?");
    if (!$stmt) throw new Exception("DB Prepare Error: " . $con->error);

    $stmt->bind_param("ssss", $new_name, $transfer_date, $transfer_time, $invoice_no);
    if (!$stmt->execute()) throw new Exception("DB Execute Error: " . $stmt->error);
    $stmt->close();

    // Success response
    ob_end_clean();
    echo json_encode([
        "status" => "success",
        "invoice_no" => $invoice_no,
        "message" => "Receipt uploaded successfully."
    ]);
    exit;

} catch (Exception $e) {
    $debug_output = ob_get_contents();
    ob_end_clean();
    if ($debug_output) {
        file_put_contents($debug_log, date("Y-m-d H:i:s") . " - " . $debug_output . "\n", FILE_APPEND);
    }

    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);
    exit;
}
