<?php

// عرض كافة الأخطاء
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../connect.php';

$driverID       = filterRequest("driverID");
$invoiceNumber  = filterRequest("invoiceNumber");
$amount         = filterRequest("amount");
$date           = filterRequest("date");
$name           = filterRequest("name");

$linkImage  = null;
$uploadDate = date("Y-m-d H:i:s");

// ✅ طباعة بيانات الإدخال للتأكد
error_log("[add_invoice.php] 📥 Data received | driverID: $driverID, invoiceNumber: $invoiceNumber, amount: $amount, date: $date");

// التحقق من وجود ملف الصورة
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $image_file       = $_FILES['image'];
    $image_name       = $image_file['name'];
    $image_extension  = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
    $allowed_extensions = ['jpg', 'jpeg', 'png'];

    if (!in_array($image_extension, $allowed_extensions)) {
        error_log("[add_invoice.php] ❌ Invalid image extension: .$image_extension");
        echo json_encode(['status' => 'error', 'message' => 'Invalid file type.']);
        exit;
    }

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $image_file['tmp_name']);
    finfo_close($finfo);

    $allowed_mime_types = ['image/jpeg', 'image/png', 'image/jpg'];
    if (!in_array($mime_type, $allowed_mime_types)) {
        error_log("[add_invoice.php] ❌ Invalid MIME type: $mime_type");
        echo json_encode(['status' => 'error', 'message' => 'Invalid file type (MIME mismatch).']);
        exit;
    }

    $new_filename = $invoiceNumber . "_" . $driverID . '.' . $image_extension;
    $target_dir   = "invoice_images/";
    $target_file  = $target_dir . $new_filename;

    if (!is_dir($target_dir)) {
        if (!mkdir($target_dir, 0755, true)) {
            error_log("[add_invoice.php] ❌ Failed to create directory: $target_dir");
        }
    }

    if (!move_uploaded_file($image_file['tmp_name'], $target_file)) {
        error_log("[add_invoice.php] ❌ Failed to move uploaded file.");
        echo json_encode(['status' => 'error', 'message' => 'Failed to upload image.']);
        exit;
    }

    $host = $_SERVER['HTTP_HOST'] ?? 'api.siromove.com';
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
    $linkImage = "$protocol://$host/siro/Admin/adminUser/invoice_images/" . $new_filename;
    error_log("[add_invoice.php] ✅ Image uploaded successfully: $linkImage");
}

try {
    $stmt = $con->prepare("INSERT INTO invoice_records (driverID, invoice_number,name, amount, date, image_link, created_at)
                           VALUES (?, ?, ?,?, ?, ?, ?)");
    $stmt->execute([$driverID, $invoiceNumber,$name, $amount, $date, $linkImage, $uploadDate]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Invoice data saved.',
        'image' => $linkImage
    ]);

    error_log("[add_invoice.php] ✅ Invoice saved successfully.");
} catch (PDOException $e) {
    $errorMsg = $e->getMessage();
    error_log("[add_invoice.php] 🛑 PDO ERROR: $errorMsg");

    echo json_encode([
        'status' => 'error',
        'message' => "Database error: $errorMsg"
    ]);
}