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

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

// Enforce granular RBAC for gatherers API
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    if (in_array($action, ['list', 'get_materials'])) {
        checkApiPagePermission($pageKey, 'view');
    }
} elseif (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true) ?? [];
    if ($action === 'save') {
        $id = trim($input['id'] ?? '');
        if (!empty($id)) {
            checkApiPagePermission($pageKey, 'edit');
        } else {
            checkApiPagePermission($pageKey, 'add');
        }
    } elseif ($action === 'delete') {
        checkApiPagePermission($pageKey, 'delete');
    }
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    if ($action === 'list') {
        $sql = "
            SELECT g.*, COALESCE(m.mat_count, 0) AS materials_count
            FROM gatherers g
            LEFT JOIN (
                SELECT jallab_id, COUNT(*) AS mat_count
                FROM materials
                GROUP BY jallab_id
            ) m ON g.id = m.jallab_id
            ORDER BY g.id DESC
        ";
        $result = $conn->query($sql);
        $gatherers = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $gatherers[] = [
                    "id"             => $row['id'],
                    "name"           => $row['name'],
                    "phone"          => $row['phone'] ?? '',
                    "notes"          => $row['notes'] ?? '',
                    "materialsCount" => (int)($row['materials_count'] ?? 0),
                    "createdAt"      => $row['created_at']
                ];
            }
        }
        echo json_encode(["status" => "success", "data" => $gatherers]);
        exit;
    }

    if ($action === 'get_materials') {
        $gatherer_id = isset($_GET['gatherer_id']) ? intval($_GET['gatherer_id']) : 0;
        if (!$gatherer_id) {
            echo json_encode(["status" => "error", "message" => "معرف الجلاب غير محدد"]);
            exit;
        }

        $stmt = $conn->prepare("
            SELECT m.*, 
                   COALESCE(AVG(fi.price), 0) AS default_price,
                   COALESCE(SUM(fi.quantity), 0) AS total_sold_qty,
                   COALESCE(SUM(fi.total), 0) AS total_sold_amount
            FROM materials m
            LEFT JOIN form_items fi ON TRIM(LOWER(fi.name)) = TRIM(LOWER(m.name))
            LEFT JOIN forms f ON fi.form_id = f.id AND f.status != 'cancelled'
            WHERE m.jallab_id = ?
            GROUP BY m.id
            ORDER BY m.id DESC
        ");
        $stmt->bind_param("i", $gatherer_id);
        $stmt->execute();
        $res = $stmt->get_result();
        $materials = [];
        while ($row = $res->fetch_assoc()) {
            $materials[] = [
                "id"              => $row['id'],
                "name"            => $row['name'],
                "unit"            => $row['unit'] ?? 'كغم',
                "defaultPrice"    => (float)($row['default_price'] ?? 0),
                "totalSoldQty"    => (float)($row['total_sold_qty'] ?? 0),
                "totalSoldAmount" => (float)($row['total_sold_amount'] ?? 0),
                "createdAt"       => $row['created_at'] ?? ''
            ];
        }
        $stmt->close();
        echo json_encode(["status" => "success", "data" => $materials]);
        exit;
    }
}

if (($_SERVER['REQUEST_METHOD'] ?? 'POST') === 'POST') {
    // Get JSON input
    $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']) : '';

        if (empty($name)) {
            echo json_encode(["status" => "error", "message" => "يرجى إدخال اسم الجلاب"]);
            exit;
        }

        // Validate name duplication
        if (!empty($id)) {
            $name_stmt = $conn->prepare("SELECT id FROM gatherers WHERE TRIM(LOWER(name)) = TRIM(LOWER(?)) AND id != ?");
            $name_stmt->bind_param("si", $name, $id);
        } else {
            $name_stmt = $conn->prepare("SELECT id FROM gatherers 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 duplication if not empty
        if (!empty($phone)) {
            if (!empty($id)) {
                $phone_stmt = $conn->prepare("SELECT id FROM gatherers WHERE phone = ? AND id != ?");
                $phone_stmt->bind_param("si", $phone, $id);
            } else {
                $phone_stmt = $conn->prepare("SELECT id FROM gatherers WHERE phone = ?");
                $phone_stmt->bind_param("s", $phone);
            }
            $phone_stmt->execute();
            $phone_stmt->store_result();
            if ($phone_stmt->num_rows > 0) {
                echo json_encode(["status" => "error", "message" => "رقم الهاتف هذا مسجل بالفعل لجلاب آخر!"]);
                $phone_stmt->close();
                exit;
            }
            $phone_stmt->close();
        }

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

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

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

        // Fetch old gatherer data for activity log
        $old_res = $conn->query("SELECT * FROM gatherers WHERE id = " . intval($id));
        $old_g = $old_res ? $old_res->fetch_assoc() : null;

        // --- Check for linked records before deleting ---
        $linked_messages = [];

        // 1. Check materials table
        $check_materials = $conn->prepare("SELECT COUNT(*) as cnt FROM materials WHERE jallab_id = ?");
        $check_materials->bind_param("i", $id);
        $check_materials->execute();
        $mat_row = $check_materials->get_result()->fetch_assoc();
        $check_materials->close();
        if ($mat_row['cnt'] > 0) {
            $linked_messages[] = "مواد مسجلة بجدول المواد (" . $mat_row['cnt'] . ")";
        }

        // 2. Check if gatherer has form sales items
        $check_sales = $conn->prepare("
            SELECT COUNT(*) as cnt
            FROM form_items fi
            INNER JOIN forms f ON fi.form_id = f.id
            INNER JOIN materials m ON TRIM(LOWER(fi.name)) = TRIM(LOWER(m.name))
            WHERE m.jallab_id = ? AND f.status != 'cancelled'
        ");
        if ($check_sales) {
            $check_sales->bind_param("i", $id);
            $check_sales->execute();
            $sales_row = $check_sales->get_result()->fetch_assoc();
            $check_sales->close();
            if ($sales_row['cnt'] > 0) {
                $linked_messages[] = "مبيعات حقيقية بالاستمارات (" . $sales_row['cnt'] . ")";
            }
        }

        if (!empty($linked_messages)) {
            $detail = implode(" و ", $linked_messages);
            echo json_encode([
                "status"  => "error",
                "message" => "عذراً، لا يمكن حذف هذا الجلاب لأنه مرتبط بـ: " . $detail . ". يرجى تعديل أو نقل السجلات المرتبطة أولاً."
            ]);
            exit;
        }
        // ------------------------------------------------

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

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