<?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 = 'materials';

// Enforce granular RBAC for materials API
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    if ($action === 'list') {
        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') {
        // Get workday start hour from settings
        $start_hour = 17; // fallback
        $settings_res = $conn->query("SELECT workday_start_hour FROM system_settings WHERE id = 1");
        if ($settings_res && $row = $settings_res->fetch_assoc()) {
            $start_hour = intval($row['workday_start_hour']);
        }

        date_default_timezone_set('Asia/Baghdad'); // Iraqi local time
        
        $now = new DateTime();
        $current_hour = (int)$now->format('H');
        
        if ($current_hour >= $start_hour) {
            // Shift started today at start_hour and ends tomorrow at start_hour
            $start = clone $now;
            $start->setTime($start_hour, 0, 0);
            
            $end = clone $now;
            $end->modify('+1 day');
            $end->setTime($start_hour, 0, 0);
        } else {
            // Shift started yesterday at start_hour and ends today at start_hour
            $start = clone $now;
            $start->modify('-1 day');
            $start->setTime($start_hour, 0, 0);
            
            $end = clone $now;
            $end->setTime($start_hour, 0, 0);
        }
        
        $start_str = $start->format('Y-m-d H:i:s');
        $end_str = $end->format('Y-m-d H:i:s');
        
        // Fetch materials with jallab name and usage count via LEFT JOIN
        $show_all = isset($_GET['show_all']) && $_GET['show_all'] === 'true';
        if ($show_all) {
            $query = "
                SELECT m.*, 
                       COALESCE(g.name, 'جلاب محذوف') AS jallab_name,
                       COALESCE(fi.usage_count, 0) AS usage_count
                FROM materials m
                LEFT JOIN gatherers g ON m.jallab_id = g.id
                LEFT JOIN (
                    SELECT TRIM(LOWER(item.name)) AS canonical_name, COUNT(*) AS usage_count
                    FROM form_items item
                    JOIN forms f ON item.form_id = f.id
                    WHERE f.status != 'cancelled'
                    GROUP BY canonical_name
                ) fi ON TRIM(LOWER(m.name)) = fi.canonical_name ";
            if (!canViewOthersData()) {
                $myId = (int)$_SESSION['user']['id'];
                $query .= " WHERE m.user_id = $myId ";
            }
            $query .= " ORDER BY m.id DESC ";
            $stmt = $conn->prepare($query);
        } else {
            $query = "
                SELECT m.*, 
                       COALESCE(g.name, 'جلاب محذوف') AS jallab_name,
                       COALESCE(fi.usage_count, 0) AS usage_count
                FROM materials m
                LEFT JOIN gatherers g ON m.jallab_id = g.id
                LEFT JOIN (
                    SELECT TRIM(LOWER(item.name)) AS canonical_name, COUNT(*) AS usage_count
                    FROM form_items item
                    JOIN forms f ON item.form_id = f.id
                    WHERE f.status != 'cancelled'
                    GROUP BY canonical_name
                ) fi ON TRIM(LOWER(m.name)) = fi.canonical_name
                WHERE m.created_at >= ? AND m.created_at < ? ";
            if (!canViewOthersData()) {
                $myId = (int)$_SESSION['user']['id'];
                $query .= " AND m.user_id = $myId ";
            }
            $query .= " ORDER BY m.id DESC ";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("ss", $start_str, $end_str);
        }
        $stmt->execute();
        $materials_res = $stmt->get_result();
        $materials = [];
        while ($row = $materials_res->fetch_assoc()) {
            $materials[] = [
                "id"             => $row['id'],
                "name"           => $row['name'],
                "accountingType" => $row['accounting_type'],
                "commissionType" => $row['commission_type'],
                "workerShareType"=> $row['worker_share_type'],
                "jallabId"       => $row['jallab_id'],
                "jallabName"     => $row['jallab_name'],
                "usageCount"     => (int)($row['usage_count'] ?? 0),
                "createdAt"      => $row['created_at']
            ];
        }
        $stmt->close();

        // Fetch gatherers (bringers) for dropdown mapping
        $gatherers_res = $conn->query("SELECT id, name FROM gatherers ORDER BY name ASC");
        $gatherers = [];
        while ($row = $gatherers_res->fetch_assoc()) {
            $gatherers[] = [
                "id" => $row['id'],
                "name" => $row['name']
            ];
        }

        echo json_encode([
            "status" => "success",
            "materials" => $materials,
            "gatherers" => $gatherers
        ]);
        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']) : '';
        $accounting_type = isset($input['accountingType']) ? trim($input['accountingType']) : '';
        $commission_type = isset($input['commissionType']) ? trim($input['commissionType']) : '';
        $worker_share_type = isset($input['workerShareType']) ? trim($input['workerShareType']) : '';
        $jallab_id = isset($input['jallabId']) ? trim($input['jallabId']) : '';

        if (empty($name) || empty($accounting_type) || empty($commission_type) || empty($worker_share_type) || empty($jallab_id)) {
            echo json_encode(["status" => "error", "message" => "يرجى ملء جميع الحقول المطلوبة"]);
            exit;
        }

        if (!empty($id)) {
            // Update
            if (!canViewOthersData()) {
                $myId = (int)$_SESSION['user']['id'];
                $chk = $conn->prepare("SELECT user_id FROM materials WHERE id = ?");
                $chk->bind_param('i', $id);
                $chk->execute();
                $m_row = $chk->get_result()->fetch_assoc();
                $chk->close();
                if ($m_row && (int)$m_row['user_id'] !== $myId) {
                    header('HTTP/1.1 403 Forbidden');
                    echo json_encode(['status' => 'error', 'message' => 'عذراً، لا تمتلك الصلاحية لتعديل هذه المادة.']);
                    exit;
                }
            }

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

            $stmt = $conn->prepare("UPDATE materials SET name = ?, accounting_type = ?, commission_type = ?, worker_share_type = ?, jallab_id = ? WHERE id = ?");
            $stmt->bind_param("ssssii", $name, $accounting_type, $commission_type, $worker_share_type, $jallab_id, $id);
            if ($stmt->execute()) {
                $new_res = $conn->query("SELECT * FROM materials WHERE id = " . intval($id));
                $new_mat = $new_res ? $new_res->fetch_assoc() : null;
                logActivity($conn, 'update', 'materials', $id, $old_mat, $new_mat);
                updateSystemState($conn, 'materials');
                echo json_encode(["status" => "success", "message" => "تم تحديث بيانات المادة بنجاح"]);
            } else {
                echo json_encode(["status" => "error", "message" => "فشل تحديث بيانات المادة"]);
            }
            $stmt->close();
        } else {
            // Insert
            $stmt = $conn->prepare("INSERT INTO materials (name, accounting_type, commission_type, worker_share_type, jallab_id, user_id) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssii", $name, $accounting_type, $commission_type, $worker_share_type, $jallab_id, $_SESSION['user']['id']);
            if ($stmt->execute()) {
                $new_id = $conn->insert_id;
                $new_res = $conn->query("SELECT * FROM materials WHERE id = " . intval($new_id));
                $new_mat = $new_res ? $new_res->fetch_assoc() : null;
                logActivity($conn, 'insert', 'materials', $new_id, null, $new_mat);
                updateSystemState($conn, 'materials');
                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;
        }
        if (!canViewOthersData()) {
            $myId = (int)$_SESSION['user']['id'];
            $chk = $conn->prepare("SELECT user_id FROM materials WHERE id = ?");
            $chk->bind_param('i', $id);
            $chk->execute();
            $m_row = $chk->get_result()->fetch_assoc();
            $chk->close();
            if ($m_row && (int)$m_row['user_id'] !== $myId) {
                header('HTTP/1.1 403 Forbidden');
                echo json_encode(['status' => 'error', 'message' => 'عذراً، لا تمتلك الصلاحية لحذف هذه المادة.']);
                exit;
            }
        }

        // --- Fetch material name first ---
        $name_stmt = $conn->prepare("SELECT name FROM materials WHERE id = ?");
        $name_stmt->bind_param("i", $id);
        $name_stmt->execute();
        $name_res = $name_stmt->get_result()->fetch_assoc();
        $name_stmt->close();

        if (!$name_res) {
            echo json_encode(["status" => "error", "message" => "المادة غير موجودة"]);
            exit;
        }
        $mat_name = $name_res['name'];

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

        // Check form_items table (linked by material name)
        $check_items = $conn->prepare("SELECT COUNT(*) as cnt FROM form_items WHERE name = ?");
        $check_items->bind_param("s", $mat_name);
        $check_items->execute();
        $items_row = $check_items->get_result()->fetch_assoc();
        $check_items->close();
        if ($items_row['cnt'] > 0) {
            $linked_messages[] = "بنود استمارات مسجلة (" . $items_row['cnt'] . ")";
        }

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

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

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

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