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

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

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

function checkFormOwnership($formId) {
    global $conn;
    if (canViewOthersData()) return;
    
    $stmt = $conn->prepare("SELECT user_id FROM forms WHERE id = ?");
    $stmt->bind_param('i', $formId);
    $stmt->execute();
    $f_user = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $myId = (int)($_SESSION['user']['id'] ?? 0);
    if ($f_user && (int)$f_user['user_id'] !== $myId) {
        header('HTTP/1.1 403 Forbidden');
        echo json_encode(['status' => 'error', 'message' => 'عذراً، لا تمتلك الصلاحية للوصول لبيانات هذه الاستمارة.']);
        exit;
    }
}

// Enforce granular RBAC for forms API
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (in_array($action, ['list', 'get', 'get_print_data'])) {
        checkApiPagePermission($pageKey, 'view');
    }
} elseif ($_SERVER['REQUEST_METHOD'] === '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 === 'save_payment') {
        // Adding repayment to invoice requires forms edit/add permission
        checkApiPagePermission($pageKey, 'edit');
    } elseif (in_array($action, ['delete', 'delete_payment'])) {
        checkApiPagePermission($pageKey, 'delete');
    }
}

// =====================================================================
// GET Requests
// =====================================================================
if ($_SERVER['REQUEST_METHOD'] === 'GET') {

    // List forms
    if ($action === 'list') {
        $whereConditions = [];
        if (!canViewOthersData()) {
            $userId = (int)$_SESSION['user']['id'];
            $whereConditions[] = "(f.user_id = $userId OR f.user_id IS NULL OR f.user_id = 0 OR f.user_id = 1)";
        }

        $isShiftFilter = (isset($_GET['shift_only']) && $_GET['shift_only'] == '1') || (isset($_GET['today_only']) && $_GET['today_only'] == '1');
        if ($isShiftFilter) {
            $settings_res = $conn->query("SELECT workday_start_hour FROM system_settings WHERE id = 1");
            $start_hour = 17; // Default 5:00 PM (17:00)
            if ($settings_res && $row = $settings_res->fetch_assoc()) {
                $start_hour = intval($row['workday_start_hour']);
            }
            $now = new DateTime('now', new DateTimeZone('Asia/Baghdad'));
            $hour = (int)$now->format('H');
            if ($hour >= $start_hour) {
                $shift_start = (clone $now)->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
                $shift_end   = (clone $now)->modify('+1 day')->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
            } else {
                $shift_start = (clone $now)->modify('-1 day')->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
                $shift_end   = (clone $now)->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
            }
            $whereConditions[] = "f.created_at >= '$shift_start' AND f.created_at < '$shift_end'";
        }

        $whereClause = "";
        if (!empty($whereConditions)) {
            $whereClause = " WHERE " . implode(" AND ", $whereConditions);
        }

        $result = $conn->query("
            SELECT f.*, COALESCE(paid_sum.paid, 0) AS total_paid
            FROM forms f
            LEFT JOIN (
                SELECT form_id, SUM(CASE WHEN type = 'deposit' OR type = 'repayment' THEN amount WHEN type = 'withdrawal' OR type = 'debt' THEN -amount ELSE 0 END) AS paid
                FROM safe_transactions
                WHERE form_id IS NOT NULL AND form_id != ''
                GROUP BY form_id
            ) paid_sum ON f.id = paid_sum.form_id
            $whereClause
            ORDER BY f.id DESC
        ");
        $rows = [];
        while ($r = $result->fetch_assoc()) {
            // Fetch items for this form
            $ist = $conn->prepare("SELECT * FROM form_items WHERE form_id = ? ORDER BY id ASC");
            $ist->bind_param('i', $r['id']);
            $ist->execute();
            $iRes  = $ist->get_result();
            $items = [];
            while ($item = $iRes->fetch_assoc()) {
                $items[] = [
                    'id'       => (string)$item['id'],
                    'name'     => $item['name'],
                    'quantity' => (int)$item['quantity'],
                    'weight'   => $item['weight']  !== null ? (float)$item['weight'] : null,
                    'price'    => (float)$item['price'],
                    'workerShare' => (float)($item['worker_share'] ?? 0),
                    'commission'  => (float)($item['commission'] ?? 0),
                    'commission_10' => (float)($item['commission_10'] ?? 0),
                    'total'       => (float)($item['total'] ?? 0)
                ];
            }
            $ist->close();

            $calcGrandTotal = calculateFormTotalPHP((int)$r['id'], $conn);
            $totalPaid = (float)$r['total_paid'];
            $status = $r['status'] ?: '0';

            // Auto-sync status in DB if fully paid
            if ($calcGrandTotal > 0 && $totalPaid >= ($calcGrandTotal - 0.01) && $status !== '1' && $status !== 'cancelled') {
                $status = '1';
                $conn->query("UPDATE forms SET status = '1', grand_total = '$calcGrandTotal' WHERE id = " . intval($r['id']));
            }

            $rows[] = [
                'id'             => (string)$r['id'],
                'customerName'   => $r['customer_name'],
                'materialsCount' => (int)$r['materials_count'],
                'status'         => $status,
                'grandTotal'     => (float)$calcGrandTotal,
                'totalPaid'      => $totalPaid,
                'isSentToPricing'=> (int)($r['is_sent_to_pricing'] ?? 0),
                'createdAt'      => $r['created_at'],
                'items'          => $items
            ];
        }
        echo json_encode(['status' => 'success', 'data' => $rows]);
        exit;
    }

    // Get items for a specific form — with material commission/worker data via LEFT JOIN
    if ($action === 'get_items') {
        $form_id = (int)($_GET['form_id'] ?? 0);
        if (!$form_id) {
            echo json_encode(['status' => 'error', 'message' => 'معرف الاستمارة مطلوب']);
            exit;
        }
        checkFormOwnership($form_id);
        $st = $conn->prepare("
            SELECT fi.*,
                   m.accounting_type,
                   m.commission_type,
                   m.worker_share_type
            FROM form_items fi
            LEFT JOIN (
                SELECT m1.name, m1.accounting_type, m1.commission_type, m1.worker_share_type
                FROM materials m1
                INNER JOIN (
                    SELECT name, MAX(id) AS max_id
                    FROM materials
                    GROUP BY name
                ) m2 ON m1.id = m2.max_id
            ) m ON fi.name = m.name
            WHERE fi.form_id = ?
            ORDER BY fi.id ASC
        ");
        $st->bind_param('i', $form_id);
        $st->execute();
        $res   = $st->get_result();
        $items = [];
        while ($r = $res->fetch_assoc()) {
            $items[] = [
                'id'             => (string)$r['id'],
                'form_id'        => (string)$r['form_id'],
                'name'           => $r['name'],
                'quantity'       => (int)$r['quantity'],
                'weight'         => $r['weight']   !== null ? (float)$r['weight'] : null,
                'price'          => (float)$r['price'],
                'accountingType' => $r['accounting_type']   ?? '',
                'commissionType' => $r['commission_type']   ?? '',
                'workerShareType'=> $r['worker_share_type'] ?? '',
                'workerShare'    => (float)($r['worker_share'] ?? 0),
                'commission'     => (float)($r['commission'] ?? 0),
                'commission_10'  => (float)($r['commission_10'] ?? 0),
                'total'          => (float)($r['total'] ?? 0)
            ];
        }
        // Fetch total paid from safe_transactions for this form
        $tst = $conn->prepare("SELECT SUM(CASE WHEN type = 'deposit' OR type = 'repayment' THEN amount WHEN type = 'withdrawal' OR type = 'debt' THEN -amount ELSE 0 END) AS paid FROM safe_transactions WHERE form_id = ?");
        $tst->bind_param('s', $form_id);
        $tst->execute();
        $paid_res = $tst->get_result()->fetch_assoc();
        $tst->close();
        $total_paid = (float)($paid_res['paid'] ?? 0);

        // Fetch customer name for this form
        $fst = $conn->prepare("SELECT customer_name FROM forms WHERE id = ?");
        $fst->bind_param('i', $form_id);
        $fst->execute();
        $f_res = $fst->get_result()->fetch_assoc();
        $fst->close();
        $customer_name = trim($f_res['customer_name'] ?? '');

        $previous_debt = 0;
        if (!empty($customer_name)) {
            // 1. Other forms unpaid balance for this customer
            $other_forms_unpaid = 0;
            $pst = $conn->prepare("
                SELECT COALESCE(SUM(f.grand_total - COALESCE((
                    SELECT SUM(CASE WHEN st.type = 'deposit' OR st.type = 'repayment' THEN st.amount WHEN st.type = 'withdrawal' OR st.type = 'debt' THEN -st.amount ELSE 0 END)
                    FROM safe_transactions st WHERE st.form_id = f.id
                ), 0)), 0) AS other_forms_unpaid
                FROM forms f
                WHERE TRIM(f.customer_name) = ? AND f.id != ? AND (f.status IS NULL OR f.status != 'cancelled')
            ");
            if ($pst) {
                $pst->bind_param('si', $customer_name, $form_id);
                $pst->execute();
                $other_forms_unpaid = (float)($pst->get_result()->fetch_assoc()['other_forms_unpaid'] ?? 0);
                $pst->close();
            }

            // 2. Manual debts unpaid balance for this customer
            $manual_unpaid = 0;
            $mst = $conn->prepare("
                SELECT COALESCE(SUM(CASE WHEN st.type = 'withdrawal' OR st.type = 'debt' THEN st.amount WHEN st.type = 'deposit' OR st.type = 'repayment' THEN -st.amount ELSE 0 END), 0) AS manual_unpaid
                FROM safe_transactions st
                JOIN debtors d ON st.debtor_id = d.id
                WHERE TRIM(d.name) = ? AND (st.form_id IS NULL OR st.form_id = 0)
            ");
            if ($mst) {
                $mst->bind_param('s', $customer_name);
                $mst->execute();
                $manual_unpaid = (float)($mst->get_result()->fetch_assoc()['manual_unpaid'] ?? 0);
                $mst->close();
            }

            $previous_debt = max(0, $other_forms_unpaid + $manual_unpaid);
        }

        $st->close();
        echo json_encode([
            'status' => 'success',
            'data' => $items,
            'totalPaid' => $total_paid,
            'previousDebt' => $previous_debt
        ]);
        exit;
    }

    // Get a single form_item by id (for inline editing)
    if ($action === 'get_item') {
        $item_id = (int)($_GET['id'] ?? 0);
        if (!$item_id) {
            echo json_encode(['status' => 'error', 'message' => 'معرف المادة مطلوب']);
            exit;
        }
        // Check ownership of the parent form
        $ost = $conn->prepare("SELECT form_id FROM form_items WHERE id = ?");
        $ost->bind_param('i', $item_id);
        $ost->execute();
        $item_form = $ost->get_result()->fetch_assoc();
        $ost->close();
        if ($item_form) {
            checkFormOwnership($item_form['form_id']);
        }
        $st = $conn->prepare("
            SELECT fi.*,
                   m.accounting_type,
                   m.commission_type,
                   m.worker_share_type
            FROM form_items fi
            LEFT JOIN (
                SELECT m1.name, m1.accounting_type, m1.commission_type, m1.worker_share_type
                FROM materials m1
                INNER JOIN (
                    SELECT name, MAX(id) AS max_id
                    FROM materials
                    GROUP BY name
                ) m2 ON m1.id = m2.max_id
            ) m ON fi.name = m.name
            WHERE fi.id = ?
            LIMIT 1
        ");
        $st->bind_param('i', $item_id);
        $st->execute();
        $r = $st->get_result()->fetch_assoc();
        $st->close();
        if (!$r) {
            echo json_encode(['status' => 'error', 'message' => 'المادة غير موجودة']);
            exit;
        }
        echo json_encode([
            'status' => 'success',
            'item'   => [
                'id'              => (string)$r['id'],
                'form_id'         => (string)$r['form_id'],
                'name'            => $r['name'],
                'quantity'        => (int)$r['quantity'],
                'weight'          => $r['weight'] !== null ? (float)$r['weight'] : null,
                'price'           => (float)$r['price'],
                'accountingType'  => $r['accounting_type']   ?? '',
                'commissionType'  => $r['commission_type']   ?? '',
                'workerShareType' => $r['worker_share_type'] ?? '',
                'workerShare'     => (float)($r['worker_share'] ?? 0),
                'commission'      => (float)($r['commission']   ?? 0),
                'commission_10'   => (float)($r['commission_10'] ?? 0),
                'total'           => (float)($r['total']        ?? 0),
            ]
        ]);
        exit;
    }

    // Get all forms in the current shift with their items
    if ($action === 'shift_forms') {
        // Calculate shift boundaries dynamically from database — Baghdad timezone
        $settings_res = $conn->query("SELECT workday_start_hour FROM system_settings WHERE id = 1");
        $start_hour = 17; // fallback to 17:00 (5:00 PM) if not configured
        if ($settings_res && $row = $settings_res->fetch_assoc()) {
            $start_hour = intval($row['workday_start_hour']);
        }

        $now  = new DateTime('now', new DateTimeZone('Asia/Baghdad'));
        $hour = (int)$now->format('H');

        if ($hour >= $start_hour) {
            $shift_start = (clone $now)->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
            $shift_end   = (clone $now)->modify('+1 day')->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
        } else {
            $shift_start = (clone $now)->modify('-1 day')->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
            $shift_end   = (clone $now)->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
        }

        // Fetch all forms in this shift
        $st = $conn->prepare(
            "SELECT f.*, COALESCE(paid_sum.paid, 0) AS total_paid
             FROM forms f
             LEFT JOIN (
                 SELECT form_id, SUM(CASE WHEN type = 'deposit' OR type = 'repayment' THEN amount WHEN type = 'withdrawal' OR type = 'debt' THEN -amount ELSE 0 END) AS paid
                 FROM safe_transactions
                 WHERE form_id IS NOT NULL AND form_id != ''
                 GROUP BY form_id
             ) paid_sum ON f.id = paid_sum.form_id
             WHERE f.created_at >= ? AND f.created_at < ?
             ORDER BY f.id DESC"
        );
        $st->bind_param('ss', $shift_start, $shift_end);
        $st->execute();
        $formsRes = $st->get_result();
        $st->close();

        $forms = [];
        while ($f = $formsRes->fetch_assoc()) {
            // Fetch items for this form
            $ist = $conn->prepare("SELECT * FROM form_items WHERE form_id = ? ORDER BY id ASC");
            $ist->bind_param('i', $f['id']);
            $ist->execute();
            $iRes  = $ist->get_result();
            $items = [];
            while ($item = $iRes->fetch_assoc()) {
                $items[] = [
                    'id'       => (string)$item['id'],
                    'name'     => $item['name'],
                    'quantity' => (int)$item['quantity'],
                    'weight'   => $item['weight']  !== null ? (float)$item['weight'] : null,
                    'price'    => (float)$item['price'],
                    'workerShare' => (float)($item['worker_share'] ?? 0),
                    'commission'  => (float)($item['commission'] ?? 0),
                    'total'       => (float)($item['total'] ?? 0)
                ];
            }
            $ist->close();

            $calcGrandTotal = calculateFormTotalPHP((int)$f['id'], $conn);
            $forms[] = [
                'id'             => (string)$f['id'],
                'customerName'   => $f['customer_name'],
                'materialsCount' => (int)$f['materials_count'],
                'status'         => $f['status'] ?: '0',
                'grandTotal'     => (float)$calcGrandTotal,
                'totalPaid'      => (float)$f['total_paid'],
                'createdAt'      => $f['created_at'],
                'items'          => $items
            ];
        }

        echo json_encode([
            'status'      => 'success',
            'data'        => $forms,
            'shift_start' => $shift_start,
            'shift_end'   => $shift_end
        ]);
        exit;
    }

    // ---------------------------------------------------------------
    // Shift Statistics — for Dashboard home page
    // ---------------------------------------------------------------
    if ($action === 'shift_stats') {
        // حساب حدود الوردية الحالية
        $settings_res = $conn->query("SELECT workday_start_hour FROM system_settings WHERE id = 1");
        $start_hour = 17;
        if ($settings_res && $row = $settings_res->fetch_assoc()) {
            $start_hour = intval($row['workday_start_hour']);
        }

        $now  = new DateTime('now', new DateTimeZone('Asia/Baghdad'));
        $hour = (int)$now->format('H');

        if ($hour >= $start_hour) {
            $shift_start = (clone $now)->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
            $shift_end   = (clone $now)->modify('+1 day')->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
        } else {
            $shift_start = (clone $now)->modify('-1 day')->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
            $shift_end   = (clone $now)->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
        }

        // 1. الاستمارات النشطة (دفعت جزئياً أو كلياً) في الوردية الحالية
        $r1 = $conn->prepare("SELECT COUNT(*) AS cnt FROM forms WHERE created_at >= ? AND created_at < ? AND (status = '1' OR status = '2')");
        $r1->bind_param('ss', $shift_start, $shift_end);
        $r1->execute();
        $active_forms = (int)$r1->get_result()->fetch_assoc()['cnt'];
        $r1->close();

        // 2. الاستمارات الغير النشطة (لم يُدفع لها شيء بعد) في الوردية الحالية
        $r2 = $conn->prepare("SELECT COUNT(*) AS cnt FROM forms WHERE created_at >= ? AND created_at < ? AND (status NOT IN ('1', '2', 'cancelled') OR status IS NULL OR status = '')");
        $r2->bind_param('ss', $shift_start, $shift_end);
        $r2->execute();
        $inactive_forms = (int)$r2->get_result()->fetch_assoc()['cnt'];
        $r2->close();

        $bags_count = 0.0;
        $bala_count = 0;

        // 5. مجموع عمولة 10% — لجميع استمارات الوردية
        $r4 = $conn->prepare("
            SELECT COALESCE(SUM(fi.commission_10), 0) AS total_comm10
            FROM form_items fi
            INNER JOIN forms f ON fi.form_id = f.id
            WHERE f.created_at >= ? AND f.created_at < ?
              AND (f.status = '1' OR f.status = '2')
        ");
        $r4->bind_param('ss', $shift_start, $shift_end);
        $r4->execute();
        $total_commission_10 = (float)($r4->get_result()->fetch_assoc()['total_comm10'] ?? 0);
        $r4->close();

        $commission_groups = []; // populated dynamically in loop below

        // 6. حق العامل — فقط للاستمارات المدفوعة جزئياً أو كلياً (status = '1' أو '2')
        $r5 = $conn->prepare("
            SELECT COALESCE(SUM(fi.worker_share), 0) AS total_worker
            FROM form_items fi
            INNER JOIN forms f ON fi.form_id = f.id
            WHERE f.created_at >= ? AND f.created_at < ?
              AND (f.status = '1' OR f.status = '2')
        ");
        $r5->bind_param('ss', $shift_start, $shift_end);
        $r5->execute();
        $total_worker_share = (float)($r5->get_result()->fetch_assoc()['total_worker'] ?? 0);
        $r5->close();

        // 6.5. مجموعات حق العامل — مجاميع حق العامل مقسمة حسب نوع حق العامل للمادة
        $r5_groups = $conn->prepare("
            SELECT COALESCE(m.worker_share_type, 'غير محدد') AS share_type, COALESCE(SUM(fi.worker_share), 0) AS total_amount
            FROM form_items fi
            INNER JOIN forms f ON fi.form_id = f.id
            LEFT JOIN (
                SELECT m1.name, m1.worker_share_type
                FROM materials m1
                INNER JOIN (
                    SELECT name, MAX(id) AS max_id
                    FROM materials
                    GROUP BY name
                ) m2 ON m1.id = m2.max_id
            ) m ON fi.name = m.name
            WHERE f.created_at >= ? AND f.created_at < ?
              AND (f.status = '1' OR f.status = '2')
            GROUP BY m.worker_share_type
        ");
        $r5_groups->bind_param('ss', $shift_start, $shift_end);
        $r5_groups->execute();
        $groups_res = $r5_groups->get_result();
        $worker_share_groups = [];
        while ($grow = $groups_res->fetch_assoc()) {
            $worker_share_groups[] = [
                'type' => $grow['share_type'],
                'amount' => (float)$grow['total_amount']
            ];
        }
        $r5_groups->close();

        // 7. المبياع — مجموع (وزن×سعر أو عدد×سعر) لجميع form_items في الوردية بدون عمولات
        $r6 = $conn->prepare("
            SELECT
                fi.quantity,
                fi.weight,
                fi.price,
                fi.name AS item_name,
                f.id AS form_id,
                m.accounting_type,
                m.commission_type
            FROM form_items fi
            INNER JOIN forms f ON fi.form_id = f.id
            LEFT JOIN materials m ON m.id = (
                SELECT MAX(m2.id) FROM materials m2
                WHERE TRIM(LOWER(m2.name)) = TRIM(LOWER(fi.name))
            )
            WHERE f.created_at >= ? AND f.created_at < ?
              AND (f.status = '1' OR f.status = '2')
        ");
        $r6->bind_param('ss', $shift_start, $shift_end);
        $r6->execute();
        $sales_res = $r6->get_result();
        $total_sales = 0.0;
        $bala_revenue = 0.0;
        $sales_groups = [];
        $sales_items = [];
        $commission_groups_map = [];

        while ($sr = $sales_res->fetch_assoc()) {
            $qty    = (int)$sr['quantity'];
            $weight = (float)($sr['weight'] ?? 0);
            $price  = (float)$sr['price'];
            $type   = $sr['accounting_type'] ?? 'عدد * سعر';
            $comm_type = $sr['commission_type'] ?? '';
            $form_id = (string)$sr['form_id'];
            $item_name = $sr['item_name'];
            
            $item_total = ($type === 'وزن * سعر')
                ? ($weight * $price)
                : ($qty * $price);
                
            if ($type === 'وزن * سعر') {
                $total_sales += $item_total;
            } else {
                $bala_revenue += $item_total;
            }
            
            if (!isset($sales_groups[$type])) {
                $sales_groups[$type] = 0.0;
            }
            $sales_groups[$type] += $item_total;

            $sales_items[] = [
                'form_id' => $form_id,
                'item_name' => $item_name,
                'quantity' => $qty,
                'weight' => $weight,
                'price' => $price,
                'accounting_type' => $type,
                'total' => $item_total
            ];

            // Calculate and aggregate commission parts
            if (!empty($comm_type) && $comm_type !== '---') {
                $parts = explode('+', $comm_type);
                foreach ($parts as $part) {
                    $trimmed_part = trim($part);
                    // Check if it's percentage commission part (e.g. 10%, 20%, 15%, etc.)
                    if (preg_match('/(\d+(?:\.\d+)?)\s*%/', $trimmed_part)) {
                        continue; // ignore percentage part from fixed commission groups
                    }
                    
                    // Evaluate this part's commission amount
                    $weight_val = $weight > 0 ? $weight : 0.0;
                    $part_amount = calcFormulaPHP($trimmed_part, $qty, $weight_val, $price, $type);
                    
                    if ($part_amount > 0) {
                        if (!isset($commission_groups_map[$trimmed_part])) {
                            $commission_groups_map[$trimmed_part] = [
                                'amount' => 0.0,
                                'qty' => 0.0
                            ];
                        }
                        $commission_groups_map[$trimmed_part]['amount'] += $part_amount;

                        // Calculate multiplier
                        if (preg_match('/(?:وزن|الوزن)/u', $trimmed_part)) {
                            $m_val = $weight > 0 ? $weight : $qty;
                        } else {
                            $m_val = $qty;
                        }
                        $commission_groups_map[$trimmed_part]['qty'] += $m_val;
                    }
                }
            }
        }
        $r6->close();

        // Convert commission groups map to array, and sum total general commission
        $bags_count = 0.0;
        $commission_groups = [];
        foreach ($commission_groups_map as $type_str => $g_info) {
            $commission_groups[] = [
                'type' => $type_str,
                'amount' => $g_info['amount'],
                'qty' => $g_info['qty']
            ];
            $bags_count += $g_info['amount'];
        }

        $sales_groups_arr = [];
        foreach ($sales_groups as $type => $amount) {
            $sales_groups_arr[] = [
                'type' => $type,
                'amount' => $amount
            ];
        }

        // 8. ديون مستحقة كافة — بدون أي تحديد وردية أو وقت
        $result_debts = $conn->query("
            SELECT d.name,
                COALESCE(SUM(CASE WHEN t.type = 'withdrawal' OR t.type = 'debt' THEN t.amount ELSE 0 END), 0) -
                COALESCE(SUM(CASE WHEN t.type = 'deposit' OR t.type = 'repayment' THEN t.amount ELSE 0 END), 0) AS manual_balance
            FROM debtors d
            LEFT JOIN safe_transactions t ON d.id = t.debtor_id AND (t.form_id IS NULL OR t.form_id = '' OR t.form_id = '0')
            GROUP BY d.id
        ");
        $debt_map = [];
        if ($result_debts) {
            while ($dr = $result_debts->fetch_assoc()) {
                $canonical = mb_strtolower(trim($dr['name']), 'UTF-8');
                if (!isset($debt_map[$canonical])) {
                    $debt_map[$canonical] = [
                        'manual_balance' => 0.0,
                        'form_balance' => 0.0
                    ];
                }
                $debt_map[$canonical]['manual_balance'] += (float)$dr['manual_balance'];
            }
        }

        $forms_sql_debts = "
            SELECT f.customer_name, f.grand_total,
                COALESCE(paid_sum.paid, 0) AS total_paid
            FROM forms f
            LEFT JOIN (
                SELECT form_id, SUM(CASE WHEN type = 'deposit' THEN amount WHEN type = 'withdrawal' THEN -amount ELSE 0 END) AS paid
                FROM safe_transactions
                WHERE form_id IS NOT NULL AND form_id != ''
                GROUP BY form_id
            ) paid_sum ON f.id = paid_sum.form_id
            WHERE f.status = '1' OR f.status = '2'
        ";
        $forms_res_debts = $conn->query($forms_sql_debts);
        if ($forms_res_debts) {
            while ($frow = $forms_res_debts->fetch_assoc()) {
                $canonical = mb_strtolower(trim($frow['customer_name']), 'UTF-8');
                if (!isset($debt_map[$canonical])) {
                    $debt_map[$canonical] = [
                        'manual_balance' => 0.0,
                        'form_balance' => 0.0
                    ];
                }
                $form_balance = (float)$frow['grand_total'] - (float)$frow['total_paid'];
                $debt_map[$canonical]['form_balance'] += $form_balance;
            }
        }

        $total_outstanding_debts = 0.0;
        foreach ($debt_map as $item) {
            $balance = $item['manual_balance'] + $item['form_balance'];
            if ($balance > 0.01) {
                $total_outstanding_debts += $balance;
            }
        }

        // 9. استلام الديون (مجموع المبالغ المقبوضة لسداد الديون/الاستمارات في هذه الوردية)
        $r_rep = $conn->prepare("
            SELECT COALESCE(SUM(
                CASE 
                    WHEN t.type = 'deposit' OR t.type = 'repayment' THEN t.amount 
                    ELSE 0 
                END
            ), 0) AS total_rep
            FROM safe_transactions t
            LEFT JOIN forms f ON f.id = t.form_id
            WHERE t.created_at >= ? AND t.created_at < ?
              AND (
                  ((t.debtor_id IS NOT NULL AND t.debtor_id != '' AND t.debtor_id != '0') AND (t.form_id IS NULL OR t.form_id = '' OR t.form_id = '0'))
                  OR
                  ((t.form_id IS NOT NULL AND t.form_id != '' AND t.form_id != '0') AND f.created_at < ?)
              )
        ");
        $r_rep->bind_param('sss', $shift_start, $shift_end, $shift_start);
        $r_rep->execute();
        $total_shift_repayments = (float)($r_rep->get_result()->fetch_assoc()['total_rep'] ?? 0);
        $r_rep->close();

        // 10. النقدي (الخزائن) — مجموع المال المستحصل في الصندوق الرئيسي خلال الوردية الحالية (باستثناء استلام الديون السابقة)
        $r_cash = $conn->prepare("
            SELECT COALESCE(
                SUM(
                    CASE 
                        WHEN t.type = 'withdrawal' THEN -t.amount
                        WHEN (t.type = 'deposit' OR t.type = 'repayment') AND (
                            ((t.debtor_id IS NOT NULL AND t.debtor_id != '' AND t.debtor_id != '0') AND (t.form_id IS NULL OR t.form_id = '' OR t.form_id = '0'))
                            OR
                            ((t.form_id IS NOT NULL AND t.form_id != '' AND t.form_id != '0') AND f.created_at < ?)
                        ) THEN 0
                        WHEN t.type = 'deposit' OR t.type = 'repayment' THEN t.amount
                        ELSE 0
                    END
                ), 0) AS total_cash
            FROM safe_transactions t
            INNER JOIN safes s ON t.safe_id = s.id
            LEFT JOIN forms f ON f.id = t.form_id
            WHERE s.type = 'primary'
              AND t.created_at >= ? AND t.created_at < ?
        ");
        $r_cash->bind_param('sss', $shift_start, $shift_start, $shift_end);
        $r_cash->execute();
        $total_shift_cash = (float)($r_cash->get_result()->fetch_assoc()['total_cash'] ?? 0);
        $r_cash->close();

        // 10.5. ديون الاستمارات اليوم (ديون الاستمارات المنشأة خلال هذه الوردية)
        $r_shift_debts = $conn->prepare("
            SELECT COALESCE(SUM(f.grand_total - COALESCE(p.paid, 0)), 0) AS shift_form_debts
            FROM forms f
            LEFT JOIN (
                SELECT form_id, SUM(CASE WHEN type = 'deposit' OR type = 'repayment' THEN amount WHEN type = 'withdrawal' OR type = 'debt' THEN -amount ELSE 0 END) AS paid
                FROM safe_transactions
                WHERE form_id IS NOT NULL AND form_id != ''
                GROUP BY form_id
            ) p ON f.id = p.form_id
            WHERE f.created_at >= ? AND f.created_at < ? AND f.status != 'cancelled'
        ");
        $r_shift_debts->bind_param('ss', $shift_start, $shift_end);
        $r_shift_debts->execute();
        $today_invoice_debts = (float)($r_shift_debts->get_result()->fetch_assoc()['shift_form_debts'] ?? 0);
        $r_shift_debts->close();

        // 10.6. تفاصيل ديون الاستمارات اليوم
        $r_shift_debts_list = $conn->prepare("
            SELECT f.id, f.customer_name, f.grand_total, COALESCE(p.paid, 0) AS paid_amount,
                   (f.grand_total - COALESCE(p.paid, 0)) AS remaining_amount
            FROM forms f
            LEFT JOIN (
                SELECT form_id, SUM(CASE WHEN type = 'deposit' THEN amount WHEN type = 'withdrawal' THEN -amount ELSE 0 END) AS paid
                FROM safe_transactions
                WHERE form_id IS NOT NULL AND form_id != ''
                GROUP BY form_id
            ) p ON f.id = p.form_id
            WHERE f.created_at >= ? AND f.created_at < ? AND f.status != 'cancelled'
            HAVING remaining_amount > 0.01
            ORDER BY f.id DESC
        ");
        $r_shift_debts_list->bind_param('ss', $shift_start, $shift_end);
        $r_shift_debts_list->execute();
        $debts_list_res = $r_shift_debts_list->get_result();
        $today_invoice_debts_list = [];
        while ($row = $debts_list_res->fetch_assoc()) {
            $today_invoice_debts_list[] = [
                'id'               => (int)$row['id'],
                'customer_name'    => $row['customer_name'],
                'grand_total'      => (float)$row['grand_total'],
                'paid_amount'      => (float)$row['paid_amount'],
                'remaining_amount' => (float)$row['remaining_amount']
            ];
        }
        $r_shift_debts_list->close();

        // 10.7. تفاصيل جميع استمارات اليوم
        $r_today_forms_list = $conn->prepare("
            SELECT f.id, f.customer_name, f.grand_total, COALESCE(p.paid, 0) AS paid_amount,
                   (f.grand_total - COALESCE(p.paid, 0)) AS remaining_amount
            FROM forms f
            LEFT JOIN (
                SELECT form_id, SUM(CASE WHEN type = 'deposit' THEN amount WHEN type = 'withdrawal' THEN -amount ELSE 0 END) AS paid
                FROM safe_transactions
                WHERE form_id IS NOT NULL AND form_id != ''
                GROUP BY form_id
            ) p ON f.id = p.form_id
            WHERE f.created_at >= ? AND f.created_at < ? AND f.status != 'cancelled'
            ORDER BY f.id DESC
        ");
        $r_today_forms_list->bind_param('ss', $shift_start, $shift_end);
        $r_today_forms_list->execute();
        $forms_list_res = $r_today_forms_list->get_result();
        $today_forms_list = [];
        while ($row = $forms_list_res->fetch_assoc()) {
            $today_forms_list[] = [
                'id'               => (int)$row['id'],
                'customer_name'    => $row['customer_name'],
                'grand_total'      => (float)$row['grand_total'],
                'paid_amount'      => (float)$row['paid_amount'],
                'remaining_amount' => (float)$row['remaining_amount']
            ];
        }
        $r_today_forms_list->close();

        echo json_encode([
            'status'              => 'success',
            'today_invoice_debts' => round($today_invoice_debts, 0),
            'today_invoice_debts_list' => $today_invoice_debts_list,
            'today_forms_list'    => $today_forms_list,
            'active_forms'        => $active_forms,
            'inactive_forms'      => $inactive_forms,
            'total_forms'         => $active_forms + $inactive_forms,
            'bags_count'          => $bags_count,
            'bala_count'          => $bala_count,
            'bala_revenue'        => round($bala_revenue, 0),
            'total_commission_10' => $total_commission_10,
            'total_worker_share'  => $total_worker_share,
            'worker_share_groups' => $worker_share_groups,
            'commission_groups'   => $commission_groups,
            'total_sales'         => round($total_sales, 0),
            'sales_groups'        => $sales_groups_arr,
            'sales_items'         => $sales_items,
            'total_outstanding_debts' => round($total_outstanding_debts, 0),
            'total_shift_repayments'   => round($total_shift_repayments, 0),
            'total_cash'          => round($total_shift_cash, 0),
            'shift_start'         => $shift_start,
            'shift_end'           => $shift_end,
            'shift_start_ts'      => (new DateTime($shift_start, new DateTimeZone('Asia/Baghdad')))->getTimestamp(),
            'shift_end_ts'        => (new DateTime($shift_end,   new DateTimeZone('Asia/Baghdad')))->getTimestamp()
        ]);
        exit;
    }
}

// =====================================================================
// POST Requests
// =====================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true) ?? [];

    // ---- Pay Form ----
    if ($action === 'pay_form') {
        $form_id = (int)($input['formId'] ?? 0);
        $safe_id = (int)($input['safeId'] ?? 0);
        $amount = (float)($input['amount'] ?? 0);
        $date = trim($input['date'] ?? '');
        $description = trim($input['description'] ?? '');

        if (!$form_id || !$safe_id || $amount < 0 || !$date || !$description) {
            echo json_encode(['status' => 'error', 'message' => 'بيانات الدفع غير مكتملة']);
            exit;
        }

        // Get the form details to make sure it exists and get customer name
        $st = $conn->prepare("SELECT * FROM forms WHERE id = ?");
        $st->bind_param('i', $form_id);
        $st->execute();
        $form = $st->get_result()->fetch_assoc();
        $st->close();

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

        $customer_name = $form['customer_name'];

        $conn->begin_transaction();
        try {
            // Update all '0' (new) forms of this customer to '2' (debt) to finalize them
            $ust = $conn->prepare("UPDATE forms SET status = '2' WHERE TRIM(LOWER(customer_name)) = TRIM(LOWER(?)) AND status = '0'");
            $ust->bind_param('s', $customer_name);
            $ust->execute();
            $ust->close();

            // Allocate the payment across forms using FIFO logic (prioritizing the current paid form first)
            allocateCustomerPayment($conn, $customer_name, $amount, $safe_id, $date, $description, null, $form_id);

            $conn->commit();

            // Fetch the final status of the clicked form to return to frontend
            $status_res = $conn->query("SELECT status FROM forms WHERE id = $form_id");
            $status_row = $status_res->fetch_assoc();
            $final_status = $status_row['status'] ?? '0';

            logActivity($conn, 'payment', 'forms', $form_id, null, ['amount' => $amount, 'customer' => $customer_name, 'description' => $description]);
            updateSystemState($conn, 'forms');
            updateSystemState($conn, 'safe_transactions');

            echo json_encode([
                'status' => 'success',
                'message' => 'تم تسجيل حركة الدفع وتوزيعها على الفواتير الأقدم بنجاح',
                'formStatus' => $final_status
            ]);
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode(['status' => 'error', 'message' => 'فشلت العملية: ' . $e->getMessage()]);
        }
        exit;
    }

    // ---- Refund Surplus (Withdrawal from form) ----
    if ($action === 'refund_surplus') {
        $form_id     = (int)($input['form_id'] ?? 0);
        $safe_id     = (int)($input['safe_id'] ?? 0);
        $amount      = (float)($input['amount'] ?? 0);
        $date        = trim($input['date'] ?? date('Y-m-d'));
        $description = trim($input['description'] ?? '');

        if (!$form_id || !$safe_id || $amount <= 0) {
            echo json_encode(['status' => 'error', 'message' => 'معلومات غير صالحة لإجراء الإرجاع']);
            exit;
        }

        // Fetch customer name
        $form_res = $conn->query("SELECT customer_name FROM forms WHERE id = $form_id");
        $form_row = $form_res->fetch_assoc();
        $customer_name = $form_row['customer_name'] ?? '';

        $debtor_id = null;
        if (!empty($customer_name)) {
            $dst = $conn->prepare("SELECT id FROM debtors WHERE TRIM(LOWER(name)) = TRIM(LOWER(?))");
            $dst->bind_param('s', $customer_name);
            $dst->execute();
            $d_res = $dst->get_result()->fetch_assoc();
            $dst->close();
            if ($d_res) {
                $debtor_id = $d_res['id'];
            }
        }

        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("INSERT INTO safe_transactions (safe_id, description, type, date, amount, form_id, debtor_id) VALUES (?, ?, 'withdrawal', ?, ?, ?, ?)");
            $stmt->bind_param('issdii', $safe_id, $description, $date, $amount, $form_id, $debtor_id);
            $stmt->execute();
            $stmt->close();

            syncCount($conn, $form_id);
            $new_tx_id = $conn->insert_id;
            $tx_res = $conn->query("SELECT * FROM safe_transactions WHERE id = " . intval($new_tx_id));
            $tx_row = $tx_res ? $tx_res->fetch_assoc() : null;
            logActivity($conn, 'insert', 'safe_transactions', $new_tx_id, null, $tx_row);
            updateSystemState($conn, 'safe_transactions');
            updateSystemState($conn, 'forms');

            $conn->commit();
            echo json_encode(['status' => 'success', 'message' => 'تم تسجيل حركة الإرجاع النقدي وتحديث الفاتورة بنجاح']);
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode(['status' => 'error', 'message' => 'فشلت العملية: ' . $e->getMessage()]);
        }
        exit;
    }

    // ---- Save Form (Add or Edit) ----
    if ($action === 'save') {
        $id     = trim($input['id'] ?? '');
        $name   = trim($input['customerName'] ?? '');
        $status = trim($input['status'] ?? '0');

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

        // Ensure customer exists in customers table
        $c_st = $conn->prepare("SELECT id FROM customers WHERE name = ?");
        $c_st->bind_param('s', $name);
        $c_st->execute();
        $c_res = $c_st->get_result();
        $c_st->close();
        if ($c_res->num_rows === 0) {
            $c_ins = $conn->prepare("INSERT INTO customers (name) VALUES (?)");
            $c_ins->bind_param('s', $name);
            $c_ins->execute();
            $c_ins->close();
        }

        $old_form = null;
        if ($id) {
            $old_res = $conn->query("SELECT * FROM forms WHERE id = " . intval($id));
            $old_form = $old_res ? $old_res->fetch_assoc() : null;

            $grand_total = calculateFormTotalPHP((int)$id, $conn);
            $tst = $conn->prepare("SELECT SUM(CASE WHEN type = 'deposit' OR type = 'repayment' THEN amount WHEN type = 'withdrawal' OR type = 'debt' THEN -amount ELSE 0 END) AS paid FROM safe_transactions WHERE form_id = ?");
            $tst->bind_param('s', $id);
            $tst->execute();
            $paid_res = $tst->get_result()->fetch_assoc();
            $tst->close();
            $total_paid = (float)($paid_res['paid'] ?? 0);

            if ($total_paid >= ($grand_total - 0.01)) {
                $status = '1';
            } elseif ($total_paid > 0.01) {
                $status = '2';
            } else {
                $curr_st = $conn->prepare("SELECT status FROM forms WHERE id = ?");
                $curr_st->bind_param('i', $id);
                $curr_st->execute();
                $curr_res = $curr_st->get_result()->fetch_assoc();
                $curr_st->close();
                $old_status = $curr_res['status'] ?? '0';
                $status = ($old_status === '1' || $old_status === '2') ? '2' : '0';
            }

            $st = $conn->prepare("UPDATE forms SET customer_name=?, status=? WHERE id=?");
            $st->bind_param('ssi', $name, $status, $id);
        } else {
            $status = '0';
            $now_baghdad = (new DateTime('now', new DateTimeZone('Asia/Baghdad')))->format('Y-m-d H:i:s');
            $my_user_id = isset($_SESSION['user']['id']) ? (int)$_SESSION['user']['id'] : 1;
            $st = $conn->prepare("INSERT INTO forms (customer_name, user_id, status, grand_total, materials_count, created_at) VALUES (?, ?, ?, 1000.00, 0, ?)");
            $st->bind_param('siss', $name, $my_user_id, $status, $now_baghdad);
        }

        if ($st->execute()) {
            $rid = $id ?: (string)$conn->insert_id;
            
            $new_res = $conn->query("SELECT * FROM forms WHERE id = " . intval($rid));
            $new_form = $new_res ? $new_res->fetch_assoc() : null;
            logActivity($conn, $id ? 'update' : 'insert', 'forms', $rid, $old_form, $new_form);
            updateSystemState($conn, 'forms');

            echo json_encode([
                'status'  => 'success',
                'message' => $id ? 'تم تحديث الاستمارة بنجاح' : 'تم إضافة الاستمارة بنجاح',
                'id'      => $rid
            ]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'فشلت العملية: ' . $conn->error]);
        }
        $st->close();
        exit;
    }

    // ---- Find existing form in current shift OR create new one ----
    if ($action === 'find_or_create') {
        $name = trim($input['customerName'] ?? '');
        if (!$name) {
            echo json_encode(['status' => 'error', 'message' => 'اسم الزبون مطلوب']);
            exit;
        }

        // Ensure customer exists in customers table
        $c_st = $conn->prepare("SELECT id FROM customers WHERE name = ?");
        $c_st->bind_param('s', $name);
        $c_st->execute();
        $c_res = $c_st->get_result();
        $c_st->close();
        if ($c_res->num_rows === 0) {
            $c_ins = $conn->prepare("INSERT INTO customers (name) VALUES (?)");
            $c_ins->bind_param('s', $name);
            $c_ins->execute();
            $c_ins->close();
        }

        // Calculate current shift boundaries dynamically from database
        $settings_res = $conn->query("SELECT workday_start_hour FROM system_settings WHERE id = 1");
        $start_hour = 17; // fallback
        if ($settings_res && $row = $settings_res->fetch_assoc()) {
            $start_hour = intval($row['workday_start_hour']);
        }

        $now   = new DateTime('now', new DateTimeZone('Asia/Baghdad'));
        $hour  = (int)$now->format('H');

        if ($hour >= $start_hour) {
            // Shift started today
            $shift_start = (clone $now)->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
            $shift_end   = (clone $now)->modify('+1 day')->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
        } else {
            // Shift started yesterday
            $shift_start = (clone $now)->modify('-1 day')->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
            $shift_end   = (clone $now)->setTime($start_hour, 0, 0)->format('Y-m-d H:i:s');
        }

        // Search for an existing open form for this customer in the current shift
        $st = $conn->prepare(
            "SELECT id FROM forms
             WHERE customer_name = ?
               AND (status = '0' OR status = 'normal')
               AND created_at >= ?
               AND created_at < ?
             ORDER BY id DESC
             LIMIT 1"
        );
        $st->bind_param('sss', $name, $shift_start, $shift_end);
        $st->execute();
        $res = $st->get_result();
        $st->close();

        if ($res->num_rows > 0) {
            // Found existing form — reuse it
            $row = $res->fetch_assoc();
            echo json_encode([
                'status'  => 'success',
                'id'      => (string)$row['id'],
                'created' => false,
                'message' => 'استمارة موجودة — تمت إضافة المادة إليها'
            ]);
        } else {
            // No form found — create a new one with explicit Baghdad timestamp
            $status = '0';
            $now_baghdad = $now->format('Y-m-d H:i:s');
            $my_user_id = isset($_SESSION['user']['id']) ? (int)$_SESSION['user']['id'] : 1;
            $ins = $conn->prepare("INSERT INTO forms (customer_name, user_id, status, materials_count, created_at) VALUES (?, ?, ?, 0, ?)");
            $ins->bind_param('siss', $name, $my_user_id, $status, $now_baghdad);
            if ($ins->execute()) {
                $new_id = $conn->insert_id;
                
                $new_res = $conn->query("SELECT * FROM forms WHERE id = " . intval($new_id));
                $new_form = $new_res ? $new_res->fetch_assoc() : null;
                logActivity($conn, 'insert', 'forms', $new_id, null, $new_form);
                updateSystemState($conn, 'forms');

                echo json_encode([
                    'status'  => 'success',
                    'id'      => (string)$new_id,
                    'created' => true,
                    'message' => 'تم إنشاء استمارة جديدة'
                ]);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'فشل إنشاء الاستمارة: ' . $conn->error]);
            }
            $ins->close();
        }
        exit;
    }

    // ---- Delete Form ----
    if ($action === 'delete') {
        $id = (int)($input['id'] ?? 0);
        if (!$id) {
            echo json_encode(['status' => 'error', 'message' => 'معرف الاستمارة مطلوب']);
            exit;
        }
        $old_res = $conn->query("SELECT * FROM forms WHERE id = " . intval($id));
        $old_form = $old_res ? $old_res->fetch_assoc() : null;

        $st = $conn->prepare("DELETE FROM forms WHERE id=?");
        $st->bind_param('i', $id);
        $ok = $st->execute();
        $st->close();
        if ($ok) {
            logActivity($conn, 'delete', 'forms', $id, $old_form, null);
            updateSystemState($conn, 'forms');
            updateSystemState($conn, 'safe_transactions'); // cascading transactions deleted
        }
        echo json_encode([
            'status'  => $ok ? 'success' : 'error',
            'message' => $ok ? 'تم حذف الاستمارة بنجاح' : 'فشل الحذف: ' . $conn->error
        ]);
        exit;
    }

    // ---- Bulk Save Item Prices ----
    if ($action === 'save_prices') {
        $form_id = (int)($input['form_id'] ?? 0);
        $items_prices = $input['items'] ?? []; // [{id: 1, price: 1500}, ...]

        if (!$form_id || empty($items_prices)) {
            echo json_encode(['status' => 'error', 'message' => 'بيانات التسعير غير مكتملة']);
            exit;
        }

        // Check view/edit permission on forms
        checkApiPagePermission($pageKey, 'edit');
        checkFormOwnership($form_id);

        $conn->begin_transaction();
        try {
            foreach ($items_prices as $ip) {
                $item_id = (int)($ip['id'] ?? 0);
                $price = (float)($ip['price'] ?? 0);

                if (!$item_id) continue;

                // Load existing item data to get quantity, weight, and name
                $stmt = $conn->prepare("SELECT * FROM form_items WHERE id = ? AND form_id = ?");
                $stmt->bind_param("ii", $item_id, $form_id);
                $stmt->execute();
                $old_item = $stmt->get_result()->fetch_assoc();
                $stmt->close();

                if (!$old_item) continue;

                $name = $old_item['name'];
                $qty = (int)$old_item['quantity'];
                $weight = $old_item['weight'] !== null ? (float)$old_item['weight'] : null;

                // Default recalculations
                $worker_share = 0;
                $commission = 0;
                $commission_10 = 0;
                $weight_val = $weight !== null ? $weight : 0.0;
                $subtotal = 0;
                $total = 0;

                // Look up material configurations
                $mst = $conn->prepare("SELECT accounting_type, commission_type, worker_share_type FROM materials WHERE TRIM(LOWER(name)) = TRIM(LOWER(?)) ORDER BY id DESC LIMIT 1");
                if ($mst) {
                    $mst->bind_param('s', $name);
                    $mst->execute();
                    $mat = $mst->get_result()->fetch_assoc();
                    $mst->close();

                    if ($mat) {
                        $acc_type = $mat['accounting_type'];
                        $comm_type = $mat['commission_type'];
                        $work_type = $mat['worker_share_type'];

                        $subtotal = ($acc_type === "وزن * سعر") ? ($weight_val * $price) : ($qty * $price);
                        $worker_share = calcFormulaPHP($work_type, $qty, $weight_val, $price, $acc_type);
                        $comm_parts = calculateCommissionPartsPHP($comm_type, $qty, $weight_val, $price, $acc_type);
                        $commission = $comm_parts['commission'];
                        $commission_10 = $comm_parts['commission_10'];
                        $total = $subtotal + $commission + $commission_10;
                    } else {
                        $subtotal = $qty * $price;
                        $total = $subtotal;
                    }
                }

                // Update form_item
                $ust = $conn->prepare("UPDATE form_items SET price = ?, worker_share = ?, commission = ?, commission_10 = ?, total = ? WHERE id = ?");
                $ust->bind_param("dddddi", $price, $worker_share, $commission, $commission_10, $total, $item_id);
                $ust->execute();
                $ust->close();

                // Log details comparison
                $new_res = $conn->query("SELECT * FROM form_items WHERE id = " . intval($item_id));
                $new_item = $new_res ? $new_res->fetch_assoc() : null;
                logActivity($conn, 'update', 'form_items', $item_id, $old_item, $new_item);
            }

            // Sync form stats
            syncCount($conn, $form_id);

            // Reset pricing assignment state
            $rst = $conn->prepare("UPDATE forms SET is_sent_to_pricing = 0 WHERE id = ?");
            $rst->bind_param("i", $form_id);
            $rst->execute();
            $rst->close();

            $conn->commit();
            updateSystemState($conn, 'forms');

            echo json_encode(['status' => 'success', 'message' => 'تم تسعير الاستمارة وحفظ التغييرات بنجاح']);
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode(['status' => 'error', 'message' => 'فشل تسعير الاستمارة: ' . $e->getMessage()]);
        }
        exit;
    }

    // ---- Send to Pricing (For Admin) ----
    if ($action === 'send_to_pricing') {
        $form_id = (int)($input['form_id'] ?? 0);
        $form_ids = isset($input['form_ids']) && is_array($input['form_ids']) ? $input['form_ids'] : [];

        if (!$form_id && empty($form_ids)) {
            echo json_encode(['status' => 'error', 'message' => 'بيانات الإرسال غير مكتملة']);
            exit;
        }

        // Check permission
        checkApiPagePermission($pageKey, 'edit');

        if (!empty($form_ids)) {
            $valid_ids = array_filter(array_map('intval', $form_ids), function($id) { return $id > 0; });
            if (!empty($valid_ids)) {
                $ids_str = implode(',', $valid_ids);
                $conn->query("UPDATE forms SET is_sent_to_pricing = 1 WHERE id IN ($ids_str)");
                updateSystemState($conn, 'forms');
                echo json_encode(['status' => 'success', 'message' => 'تم إرسال الاستمارات المحددة للتسعير بنجاح']);
                exit;
            }
        }

        checkFormOwnership($form_id);

        $stmt = $conn->prepare("UPDATE forms SET is_sent_to_pricing = 1 WHERE id = ?");
        $stmt->bind_param("i", $form_id);
        $ok = $stmt->execute();
        $stmt->close();

        if ($ok) {
            logActivity($conn, 'update', 'forms', $form_id, ['is_sent_to_pricing' => 0], ['is_sent_to_pricing' => 1]);
            updateSystemState($conn, 'forms');
            echo json_encode(['status' => 'success', 'message' => 'تم إرسال الاستمارة للتسعير بنجاح']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'فشل إرسال الاستمارة للتسعير: ' . $conn->error]);
        }
        exit;
    }

    // ---- Save Item (Add or Edit) ----
    if ($action === 'save_item') {
        $item_id = trim($input['id'] ?? '');
        $form_id = (int)($input['form_id'] ?? 0);
        $name    = trim($input['name'] ?? '');
        $qty     = (int)($input['quantity'] ?? 0);
        $price   = (float)($input['price'] ?? 0);
        $worker_share = (float)($input['worker_share'] ?? 0);
        $commission   = (float)($input['commission'] ?? 0);
        $commission_10 = (float)($input['commission_10'] ?? 0);
        $total        = (float)($input['total'] ?? 0);

        // Handle nullable fields safely
        $weight = (isset($input['weight']) && $input['weight'] !== '' && $input['weight'] !== null)
                  ? (float)$input['weight'] : null;

        if (!$name || !$form_id) {
            echo json_encode(['status' => 'error', 'message' => 'بيانات المادة غير مكتملة']);
            exit;
        }
        // للإضافة فقط: العدد يجب أن يكون >= 1
        if (!$item_id && $qty < 1) {
            echo json_encode(['status' => 'error', 'message' => 'يجب إدخال عدد صحيح أكبر من صفر']);
            exit;
        }

        // Look up material configurations to compute values automatically on the backend
        $mst = $conn->prepare("SELECT accounting_type, commission_type, worker_share_type FROM materials WHERE TRIM(LOWER(name)) = TRIM(LOWER(?)) ORDER BY id DESC LIMIT 1");
        if ($mst) {
            $mst->bind_param('s', $name);
            $mst->execute();
            $mat = $mst->get_result()->fetch_assoc();
            $mst->close();

            if ($mat) {
                $acc_type = $mat['accounting_type'];
                $comm_type = $mat['commission_type'];
                $work_type = $mat['worker_share_type'];

                $weight_val = $weight !== null ? $weight : 0.0;
                $subtotal = ($acc_type === "وزن * سعر") ? ($weight_val * $price) : ($qty * $price);
                
                $worker_share = calcFormulaPHP($work_type, $qty, $weight_val, $price, $acc_type);
                
                $comm_parts = calculateCommissionPartsPHP($comm_type, $qty, $weight_val, $price, $acc_type);
                $commission = $comm_parts['commission'];
                $commission_10 = $comm_parts['commission_10'];
                
                $total = $subtotal + $commission + $commission_10;
            }
        }

        if ($item_id) {
            // Update
            $old_res = $conn->query("SELECT * FROM form_items WHERE id = " . intval($item_id));
            $old_item = $old_res ? $old_res->fetch_assoc() : null;

            $st = $conn->prepare(
                "UPDATE form_items SET name=?, quantity=?, weight=?, price=?, worker_share=?, commission=?, commission_10=?, total=? WHERE id=?"
            );
            $st->bind_param('siidddddi', $name, $qty, $weight, $price, $worker_share, $commission, $commission_10, $total, $item_id);
            $ok = $st->execute();
            $st->close();
            if ($ok) {
                syncCount($conn, $form_id);
                $new_res = $conn->query("SELECT * FROM form_items WHERE id = " . intval($item_id));
                $new_item = $new_res ? $new_res->fetch_assoc() : null;
                logActivity($conn, 'update', 'form_items', $item_id, $old_item, $new_item);
                updateSystemState($conn, 'forms');
            }
            echo json_encode([
                'status'  => $ok ? 'success' : 'error',
                'message' => $ok ? 'تم تحديث المادة بنجاح' : 'فشل التحديث: ' . $conn->error
            ]);
        } else {
            // Insert — use query() with escaped values to avoid nullable bind_param issues
            $e_name   = $conn->real_escape_string($name);
            $e_weight = ($weight !== null) ? (float)$weight : 'NULL';
            $sql = "INSERT INTO form_items (form_id, name, quantity, weight, price, worker_share, commission, commission_10, total)
                    VALUES ($form_id, '$e_name', $qty, $e_weight, $price, $worker_share, $commission, $commission_10, $total)";
            if ($conn->query($sql)) {
                $new_id = $conn->insert_id;
                syncCount($conn, $form_id);
                
                $new_res = $conn->query("SELECT * FROM form_items WHERE id = " . intval($new_id));
                $new_item = $new_res ? $new_res->fetch_assoc() : null;
                logActivity($conn, 'insert', 'form_items', $new_id, null, $new_item);
                updateSystemState($conn, 'forms');

                echo json_encode([
                    'status'  => 'success',
                    'message' => 'تم إضافة المادة بنجاح',
                    'id'      => (string)$new_id
                ]);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'فشل الإضافة: ' . $conn->error]);
            }
        }
        exit;
    }

    // ---- Delete Item ----
    if ($action === 'delete_item') {
        $item_id = (int)($input['id'] ?? 0);
        $form_id = (int)($input['form_id'] ?? 0);
        if (!$item_id) {
            echo json_encode(['status' => 'error', 'message' => 'معرف المادة مطلوب']);
            exit;
        }
        $old_res = $conn->query("SELECT * FROM form_items WHERE id = " . intval($item_id));
        $old_item = $old_res ? $old_res->fetch_assoc() : null;

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

// Sync materials_count and grand_total to match actual count in form_items
function syncCount($conn, $form_id) {
    $form_id = (int)$form_id;
    $r = $conn->query("SELECT COUNT(*) AS c FROM form_items WHERE form_id = $form_id");
    $c = (int)$r->fetch_assoc()['c'];
    $grand_total = calculateFormTotalPHP($form_id, $conn);
    
    // Recalculate status based on payments made
    $tst = $conn->prepare("SELECT SUM(CASE WHEN type = 'deposit' OR type = 'repayment' THEN amount WHEN type = 'withdrawal' OR type = 'debt' THEN -amount ELSE 0 END) AS paid FROM safe_transactions WHERE form_id = ?");
    $tst->bind_param('s', $form_id);
    $tst->execute();
    $paid_res = $tst->get_result()->fetch_assoc();
    $tst->close();
    $total_paid = (float)($paid_res['paid'] ?? 0);

    if ($total_paid >= ($grand_total - 0.01)) {
        $status = '1';
    } elseif ($total_paid > 0.01) {
        $status = '2';
    } else {
        $curr_st = $conn->prepare("SELECT status FROM forms WHERE id = ?");
        $curr_st->bind_param('i', $form_id);
        $curr_st->execute();
        $curr_res = $curr_st->get_result()->fetch_assoc();
        $curr_st->close();
        $old_status = $curr_res['status'] ?? '0';
        $status = ($old_status === '1' || $old_status === '2') ? '2' : '0';
    }

    $ust = $conn->prepare("UPDATE forms SET materials_count = ?, grand_total = ?, status = ? WHERE id = ?");
    $ust->bind_param('idsi', $c, $grand_total, $status, $form_id);
    $ust->execute();
    $ust->close();
}

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