<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/db.php';

$action = isset($_GET['action']) ? $_GET['action'] : '';
$pageKey = 'customers';

$publicActions = ['upsert'];
if (!in_array($action, $publicActions)) {
    require_once __DIR__ . '/../includes/auth_middleware.php';
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    if ($action === 'list') {
        checkApiPagePermission($pageKey, 'view');
        $sql = "
            SELECT c.*, COALESCE(f.forms_count, 0) AS forms_count
            FROM customers c
            LEFT JOIN (
                SELECT TRIM(LOWER(customer_name)) AS canonical_name, COUNT(*) AS forms_count
                FROM forms
                WHERE status != 'cancelled'
                GROUP BY canonical_name
            ) f ON TRIM(LOWER(c.name)) = f.canonical_name
            ORDER BY c.id DESC
        ";
        $result = $conn->query($sql);
        $customers = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $customers[] = [
                    "id"         => $row['id'],
                    "name"       => $row['name'],
                    "phone"      => $row['phone'] ?? "",
                    "notes"      => $row['notes'] ?? "",
                    "status"     => $row['status'] ?? "active",
                    "formsCount" => (int)($row['forms_count'] ?? 0),
                    "createdAt"  => $row['created_at']
                ];
            }
        }
        echo json_encode(["status" => "success", "data" => $customers]);
        exit;
    }
}

if (($_SERVER['REQUEST_METHOD'] ?? 'POST') === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true) ?? [];
    
    if ($action === 'save') {
        $id     = isset($input['id']) ? trim($input['id']) : '';
        $name   = isset($input['name']) ? trim($input['name']) : '';
        $phone  = isset($input['phone']) ? trim($input['phone']) : '';
        $notes  = isset($input['notes']) ? trim($input['notes']) : '';
        $status = isset($input['status']) ? trim($input['status']) : 'active';

        if (empty($name)) {
            echo json_encode(["status" => "error", "message" => "اسم الزبون مطلوب"]);
            exit;
        }

        if (!empty($id)) {
            checkApiPagePermission($pageKey, 'edit');
        } else {
            checkApiPagePermission($pageKey, 'add');
        }

        // Validate name duplication using TRIM(LOWER(name))
        if (!empty($id)) {
            $name_stmt = $conn->prepare("SELECT id FROM customers WHERE TRIM(LOWER(name)) = TRIM(LOWER(?)) AND id != ?");
            $name_stmt->bind_param("si", $name, $id);
        } else {
            $name_stmt = $conn->prepare("SELECT id FROM customers WHERE TRIM(LOWER(name)) = TRIM(LOWER(?))");
            $name_stmt->bind_param("s", $name);
        }
        $name_stmt->execute();
        $name_stmt->store_result();
        if ($name_stmt->num_rows > 0) {
            echo json_encode(["status" => "error", "message" => "اسم الزبون هذا مسجل بالفعل لزبون آخر!"]);
            $name_stmt->close();
            exit;
        }
        $name_stmt->close();

        // Validate phone number duplication if not empty
        if (!empty($phone)) {
            if (!empty($id)) {
                $dup_stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ? AND id != ?");
                $dup_stmt->bind_param("si", $phone, $id);
            } else {
                $dup_stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ?");
                $dup_stmt->bind_param("s", $phone);
            }
            $dup_stmt->execute();
            $dup_stmt->store_result();
            if ($dup_stmt->num_rows > 0) {
                echo json_encode(["status" => "error", "message" => "رقم الهاتف هذا مسجل بالفعل لزبون آخر!"]);
                $dup_stmt->close();
                exit;
            }
            $dup_stmt->close();
        }

        if (!empty($id)) {
            // Update
            $old_res = $conn->query("SELECT * FROM customers WHERE id = " . intval($id));
            $old_c = $old_res ? $old_res->fetch_assoc() : null;

            $stmt = $conn->prepare("UPDATE customers SET name = ?, phone = ?, notes = ?, status = ? WHERE id = ?");
            $stmt->bind_param("ssssi", $name, $phone, $notes, $status, $id);
            if ($stmt->execute()) {
                $new_res = $conn->query("SELECT * FROM customers WHERE id = " . intval($id));
                $new_c = $new_res ? $new_res->fetch_assoc() : null;
                logActivity($conn, 'update', 'customers', $id, $old_c, $new_c);
                updateSystemState($conn, 'customers');
                echo json_encode(["status" => "success", "message" => "تم تحديث بيانات الزبون بنجاح"]);
            } else {
                echo json_encode(["status" => "error", "message" => "فشل تحديث بيانات الزبون"]);
            }
            $stmt->close();
        } else {
            // Insert
            $stmt = $conn->prepare("INSERT INTO customers (name, phone, notes, status) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $name, $phone, $notes, $status);
            if ($stmt->execute()) {
                $new_id = $conn->insert_id;
                $new_res = $conn->query("SELECT * FROM customers WHERE id = " . intval($new_id));
                $new_c = $new_res ? $new_res->fetch_assoc() : null;
                logActivity($conn, 'insert', 'customers', $new_id, null, $new_c);
                updateSystemState($conn, 'customers');
                echo json_encode(["status" => "success", "message" => "تم إضافة الزبون بنجاح"]);
            } else {
                echo json_encode(["status" => "error", "message" => "فشل إضافة الزبون"]);
            }
            $stmt->close();
        }
        exit;
    }

    if ($action === 'toggle_status') {
        checkApiPagePermission($pageKey, 'edit');
        $id = isset($input['id']) ? trim($input['id']) : '';
        $status = isset($input['status']) ? trim($input['status']) : '';

        if (empty($id) || empty($status)) {
            echo json_encode(["status" => "error", "message" => "معلومات غير كاملة لتحديث الحالة"]);
            exit;
        }

        $old_res = $conn->query("SELECT * FROM customers WHERE id = " . intval($id));
        $old_c = $old_res ? $old_res->fetch_assoc() : null;

        $stmt = $conn->prepare("UPDATE customers SET status = ? WHERE id = ?");
        $stmt->bind_param("si", $status, $id);
        if ($stmt->execute()) {
            $new_res = $conn->query("SELECT * FROM customers WHERE id = " . intval($id));
            $new_c = $new_res ? $new_res->fetch_assoc() : null;
            logActivity($conn, 'update', 'customers', $id, $old_c, $new_c);
            updateSystemState($conn, 'customers');
            echo json_encode(["status" => "success", "message" => "تم تعديل حالة الحساب بنجاح"]);
        } else {
            echo json_encode(["status" => "error", "message" => "فشل تعديل حالة الحساب"]);
        }
        $stmt->close();
        exit;
    }

    if ($action === 'delete') {
        checkApiPagePermission($pageKey, 'delete');
        $id = isset($input['id']) ? trim($input['id']) : '';
        if (empty($id)) {
            echo json_encode(["status" => "error", "message" => "معرف الزبون غير موجود"]);
            exit;
        }

        // Fetch customer name
        $stmt_c = $conn->prepare("SELECT * FROM customers WHERE id = ?");
        $stmt_c->bind_param("i", $id);
        $stmt_c->execute();
        $customer = $stmt_c->get_result()->fetch_assoc();
        $stmt_c->close();

        if (!$customer) {
            echo json_encode(["status" => "error", "message" => "الزبون غير موجود"]);
            exit;
        }

        $customer_name = $customer['name'];

        // 1. Check forms table for linked records
        $stmt_f = $conn->prepare("SELECT COUNT(*) AS cnt FROM forms WHERE TRIM(LOWER(customer_name)) = TRIM(LOWER(?))");
        $stmt_f->bind_param("s", $customer_name);
        $stmt_f->execute();
        $f_res = $stmt_f->get_result()->fetch_assoc();
        $stmt_f->close();

        if ($f_res && $f_res['cnt'] > 0) {
            echo json_encode(["status" => "error", "message" => "لا يمكن حذف هذا الزبون لارتباطه باستمارات محاسبية قائمة (" . $f_res['cnt'] . ")"]);
            exit;
        }

        // 2. Check safe transactions linked to this debtor
        $stmt_t = $conn->prepare("SELECT COUNT(*) AS cnt FROM safe_transactions WHERE debtor_id IN (SELECT id FROM debtors WHERE TRIM(LOWER(name)) = TRIM(LOWER(?)))");
        $stmt_t->bind_param("s", $customer_name);
        $stmt_t->execute();
        $t_res = $stmt_t->get_result()->fetch_assoc();
        $stmt_t->close();

        if ($t_res && $t_res['cnt'] > 0) {
            echo json_encode(["status" => "error", "message" => "لا يمكن حذف هذا الزبون لوجود حركات مالية مسجلة باسمه في كشف الديون والتحصيلات (" . $t_res['cnt'] . ")"]);
            exit;
        }

        $stmt = $conn->prepare("DELETE FROM customers WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            logActivity($conn, 'delete', 'customers', $id, $customer, null);
            updateSystemState($conn, 'customers');
            echo json_encode(["status" => "success", "message" => "تم حذف الزبون بنجاح"]);
        } else {
            echo json_encode(["status" => "error", "message" => "فشل حذف الزبون"]);
        }
        $stmt->close();
        exit;
    }

    if ($action === 'upsert') {
        $name = isset($input['name']) ? trim($input['name']) : '';

        if (empty($name)) {
            echo json_encode(["status" => "error", "message" => "اسم الزبون مطلوب"]);
            exit;
        }

        // Check if customer already exists (case-insensitive & trimmed)
        $check = $conn->prepare("SELECT id, name FROM customers WHERE TRIM(LOWER(name)) = TRIM(LOWER(?)) LIMIT 1");
        $check->bind_param("s", $name);
        $check->execute();
        $result = $check->get_result();
        $check->close();

        if ($result->num_rows > 0) {
            // Customer already exists — return their ID
            $existing = $result->fetch_assoc();
            echo json_encode([
                "status"  => "success",
                "message" => "الزبون موجود مسبقاً",
                "id"      => $existing['id'],
                "added"   => false
            ]);
        } else {
            // Customer not found — insert new record
            $stmt = $conn->prepare("INSERT INTO customers (name, phone, notes, status) VALUES (?, '', '', 'active')");
            $stmt->bind_param("s", $name);
            if ($stmt->execute()) {
                $new_id = $conn->insert_id;
                $new_res = $conn->query("SELECT * FROM customers WHERE id = " . intval($new_id));
                $new_c = $new_res ? $new_res->fetch_assoc() : null;
                logActivity($conn, 'insert', 'customers', $new_id, null, $new_c);
                updateSystemState($conn, 'customers');
                echo json_encode([
                    "status"  => "success",
                    "message" => "تم إضافة الزبون تلقائياً",
                    "id"      => $new_id,
                    "added"   => true
                ]);
            } else {
                echo json_encode(["status" => "error", "message" => "فشل إضافة الزبون"]);
            }
            $stmt->close();
        }
        exit;
    }
}

echo json_encode(["status" => "error", "message" => "طلب غير صالح"]);
?>
