<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once "db.php";

// التحقق من تسجيل الدخول
$UID = isset($_SESSION['UID']) ? intval($_SESSION['UID']) : null;
if (!$UID) {
    echo json_encode(["status" => "error", "message" => "❌ يجب تسجيل الدخول أولاً"]);
    exit;
}

// استقبال البيانات
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);

// تحقق من وصول البيانات الأساسية
if (
    !$data ||
    !isset($data['project_id']) ||
    !isset($data['item']) ||
    !isset($data['dateAddRe']) ||
    !isset($data['item_price']) ||
    !isset($data['unit']) ||
    !isset($data['quantity']) ||
    !isset($data['total_price']) ||
    !isset($data['contractor']) ||
    !isset($data['deduct_reason']) ||
    !isset($data['employee-id']) // ✅ الموظف إلزامي
) {
    echo json_encode(["status" => "error", "message" => "❌ بيانات ناقصة"]);
    exit;
}

// استخراج القيم
$project_id   = intval($data['project_id']);
$invoice      = trim($data['item']);
$date         = trim($data['dateAddRe']);
$item_price   = floatval($data['item_price']);
$unit         = trim($data['unit']);
$quantity     = floatval($data['quantity']);
$total_price  = floatval($data['total_price']);
$supplier     = trim($data['contractor']);
$payment      = trim($data['deduct_reason']);
$emp_id       = intval($data['employee-id']); // ✅ رقم الموظف
$attachment   = isset($data['AttachmentPath']) ? trim($data['AttachmentPath']) : null;
$notes        = isset($data['notes']) ? trim($data['notes']) : null;

// تنفيذ الإدخال في جدول المصروفات
$sql = "INSERT INTO expensesMH (
            project_id, invoice_number, date, item_price, unit, quantity, total_price,
            supplier, payment_method, EmpID, AttachmentPath, notes
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param(
    "issdssdssiss",
    $project_id, $invoice, $date, $item_price, $unit, $quantity, $total_price,
    $supplier, $payment, $emp_id, $attachment, $notes
);

if ($stmt->execute()) {
    // ✅ تم حفظ المصروف، الآن نسجل العملية في TransactionsMH
    $sql2 = "INSERT INTO TransactionsMH (
                method, date, value, RefranNUM, type, user_id, user_idCST, AttachmentPath, notes
            ) VALUES (?, ?, ?, ?, 'مخرج', ?, ?, ?, ?)";

    $stmt2 = $conn->prepare($sql2);
    $stmt2->bind_param(
        "ssdsiiss",
        $payment, $date, $total_price, $invoice, $UID, $UID, $attachment, $notes
    );

    if ($stmt2->execute()) {
        echo json_encode(["status" => "success", "message" => "✅ تم حفظ المصروف وتسجيل العملية بنجاح"]);
    } else {
        echo json_encode(["status" => "error", "message" => "❌ حفظ المصروف تم، لكن فشل تسجيل العملية", "error" => $stmt2->error]);
    }

    $stmt2->close();
} else {
    echo json_encode(["status" => "error", "message" => "❌ فشل في حفظ المصروف", "error" => $stmt->error]);
}

$stmt->close();
$conn->close();
?>