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

// Safe session start
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$pageKey = 'calibration';

// Check view permission for all GET requests
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    checkApiPagePermission($pageKey, 'view');
    
    $action = isset($_GET['action']) ? $_GET['action'] : 'shift_calibration';
    
    // =========================================================
    // 1. Shift Calibration Calculation (نفس منطق الصفحة الرئيسية shift_stats)
    // =========================================================
    if ($action === 'shift_calibration') {
        // Calculate current shift boundaries dynamically from system_settings
        $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');
        }

        // 1. Active Forms Count (نفس الاستمارات النشطة بالصفحة الرئيسية)
        $r_active = $conn->prepare("SELECT COUNT(*) AS cnt FROM forms WHERE created_at >= ? AND created_at < ? AND (status = '1' OR status = '2')");
        $r_active->bind_param('ss', $shift_start, $shift_end);
        $r_active->execute();
        $active_forms = (int)($r_active->get_result()->fetch_assoc()['cnt'] ?? 0);
        $r_active->close();

        // رسم الاستمارات (عدد الاستمارات × 1000)
        $forms_fee_total = $active_forms * 1000;

        // 2. Percentage Commission Total (نفس مجموع عمولة 10% بالصفحة الرئيسية)
        $r_comm10 = $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')
        ");
        $r_comm10->bind_param('ss', $shift_start, $shift_end);
        $r_comm10->execute();
        $total_commission_10 = (float)($r_comm10->get_result()->fetch_assoc()['total_comm10'] ?? 0);
        $r_comm10->close();

        // 3. Sales (مبياع), Bala (بلا), & Bags (أكياس) (نفس منطق الصفحة الرئيسية)
        $r_items = $conn->prepare("
            SELECT
                fi.id,
                fi.form_id,
                fi.quantity,
                fi.weight,
                fi.price,
                fi.commission_10,
                fi.name AS item_name,
                f.customer_name,
                f.created_at AS form_date,
                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')
        ");
        $r_items->bind_param('ss', $shift_start, $shift_end);
        $r_items->execute();
        $items_res = $r_items->get_result();

        $total_sales = 0.0;
        $bala_revenue = 0.0;
        $bags_count = 0.0;

        $sales_items = [];
        $bala_items = [];
        $commission_items = [];
        $bags_items = [];

        while ($sr = $items_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'];
            $customer_name = $sr['customer_name'];
            $comm_10 = (float)($sr['commission_10'] ?? 0);

            $item_total = ($type === 'وزن * سعر')
                ? ($weight * $price)
                : ($qty * $price);

            $item_data = [
                'id' => $sr['id'],
                'form_id' => $form_id,
                'customer_name' => $customer_name,
                'item_name' => $item_name,
                'quantity' => $qty,
                'weight' => $weight,
                'price' => $price,
                'accounting_type' => $type,
                'item_value' => $item_total,
                'commission_10' => $comm_10,
                'commission' => 0.0,
                'form_date' => $sr['form_date']
            ];

            if ($type === 'وزن * سعر') {
                $total_sales += $item_total;
                $sales_items[] = $item_data;
            } else {
                $bala_revenue += $item_total;
                $bala_items[] = $item_data;
            }

            if ($comm_10 > 0) {
                $commission_items[] = $item_data;
            }

            // العمولات الثابتة (أكياس) — نفس دالة حساب الصفحة الرئيسية calcFormulaPHP
            if (!empty($comm_type) && $comm_type !== '---') {
                $parts = explode('+', $comm_type);
                $item_bags = 0.0;
                foreach ($parts as $part) {
                    $trimmed_part = trim($part);
                    if (preg_match('/(\d+(?:\.\d+)?)\s*%/', $trimmed_part)) {
                        continue; // استبعاد العمولات المئوية
                    }
                    $weight_val = $weight > 0 ? $weight : 0.0;
                    $part_amount = calcFormulaPHP($trimmed_part, $qty, $weight_val, $price, $type);
                    if ($part_amount > 0) {
                        $bags_count += $part_amount;
                        $item_bags += $part_amount;
                    }
                }
                if ($item_bags > 0) {
                    $item_data['commission'] = $item_bags;
                    $bags_items[] = $item_data;
                }
            }
        }
        $r_items->close();

        // المجموع الكلي للإيرادات (مجموع ما سبق)
        $grand_total = $bala_revenue + $total_sales + $total_commission_10 + $bags_count + $forms_fee_total;

        // 4. Shift Cash & Shift Debts (النقدي والديون بنفس منطق الصفحة الرئيسية)
        $r_cash_debts = $conn->prepare("
            SELECT
                COALESCE(SUM(COALESCE(p.paid, 0)), 0) AS shift_cash_total,
                COALESCE(SUM(f.grand_total - COALESCE(p.paid, 0)), 0) AS shift_debts_total
            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 = '1' OR f.status = '2')
        ");
        $r_cash_debts->bind_param('ss', $shift_start, $shift_end);
        $r_cash_debts->execute();
        $cd_row = $r_cash_debts->get_result()->fetch_assoc();
        $r_cash_debts->close();

        $shift_cash_total = round((float)($cd_row['shift_cash_total'] ?? 0), 2);
        $shift_debts_total = round((float)($cd_row['shift_debts_total'] ?? 0), 2);
        $cash_debts_sum = round($shift_cash_total + $shift_debts_total, 2);

        // نسبة المطابقة
        $difference = round($grand_total - $cash_debts_sum, 2);
        $is_matching = abs($difference) <= 0.01;

        echo json_encode([
            'status' => 'success',
            'shift_info' => [
                'shift_start' => $shift_start,
                'shift_end' => $shift_end,
                'workday_start_hour' => $start_hour
            ],
            'calibration' => [
                'bala_total' => round($bala_revenue, 2),
                'sales_total' => round($total_sales, 2),
                'percentage_commission_total' => round($total_commission_10, 2),
                'bags_commission_total' => round($bags_count, 2),
                'forms_count' => $active_forms,
                'forms_fee_total' => round($forms_fee_total, 2),
                'grand_total' => round($grand_total, 2),
                
                // Section 2: Cash & Debts
                'shift_cash_total' => $shift_cash_total,
                'shift_debts_total' => $shift_debts_total,
                'cash_debts_sum' => $cash_debts_sum,

                // Section 3: Audit Matching Verification
                'is_matching' => $is_matching,
                'difference' => $difference
            ],
            'details' => [
                'bala_items' => $bala_items,
                'sales_items' => $sales_items,
                'commission_items' => $commission_items,
                'bags_items' => $bags_items
            ]
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // =========================================================
    // 2. Manual Calibration Records List
    // =========================================================
    if ($action === 'list') {
        $result = $conn->query("SELECT * FROM `calibrations` ORDER BY `id` DESC");
        $calibrations = [];
        
        $totalDevices = 0;
        $calibratedCount = 0;
        $needsAdjustmentCount = 0;
        $totalVariance = 0;
        
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $refVal = (float)$row['reference_value'];
                $measVal = (float)$row['measured_value'];
                $varVal = (float)$row['variance'];
                
                $totalDevices++;
                if ($row['status'] === 'calibrated') {
                    $calibratedCount++;
                } else if ($row['status'] === 'needs_adjustment') {
                    $needsAdjustmentCount++;
                }
                $totalVariance += abs($varVal);

                $calibrations[] = [
                    'id' => (int)$row['id'],
                    'device_name' => $row['device_name'],
                    'device_code' => $row['device_code'] ?? '',
                    'calibration_type' => $row['calibration_type'],
                    'reference_value' => $refVal,
                    'measured_value' => $measVal,
                    'variance' => $varVal,
                    'unit' => $row['unit'] ?? 'كجم',
                    'status' => $row['status'],
                    'calibration_date' => $row['calibration_date'],
                    'next_calibration_date' => $row['next_calibration_date'] ?? '',
                    'technician' => $row['technician'] ?? '',
                    'notes' => $row['notes'] ?? '',
                    'created_at' => $row['created_at']
                ];
            }
        }
        
        $avgVariance = $totalDevices > 0 ? round($totalVariance / $totalDevices, 3) : 0;
        
        echo json_encode([
            'status' => 'success',
            'data' => $calibrations,
            'stats' => [
                'total_devices' => $totalDevices,
                'calibrated_count' => $calibratedCount,
                'needs_adjustment_count' => $needsAdjustmentCount,
                'avg_variance' => $avgVariance
            ]
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_GET['action']) ? $_GET['action'] : '';
    $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
    
    if ($action === 'save') {
        $id = isset($input['id']) ? trim($input['id']) : '';
        
        if (empty($id)) {
            checkApiPagePermission($pageKey, 'add');
        } else {
            checkApiPagePermission($pageKey, 'edit');
        }
        
        $deviceName = isset($input['device_name']) ? trim($input['device_name']) : '';
        $deviceCode = isset($input['device_code']) ? trim($input['device_code']) : '';
        $calibrationType = isset($input['calibration_type']) ? trim($input['calibration_type']) : 'معايرة وزن قياسي';
        $referenceValue = isset($input['reference_value']) ? (float)$input['reference_value'] : 0.0;
        $measuredValue = isset($input['measured_value']) ? (float)$input['measured_value'] : 0.0;
        $unit = isset($input['unit']) ? trim($input['unit']) : 'كجم';
        $status = isset($input['status']) ? trim($input['status']) : 'calibrated';
        $calibrationDate = isset($input['calibration_date']) && !empty($input['calibration_date']) ? trim($input['calibration_date']) : date('Y-m-d');
        $nextCalibrationDate = isset($input['next_calibration_date']) && !empty($input['next_calibration_date']) ? trim($input['next_calibration_date']) : null;
        $technician = isset($input['technician']) ? trim($input['technician']) : '';
        $notes = isset($input['notes']) ? trim($input['notes']) : '';
        
        if (empty($deviceName)) {
            echo json_encode(['status' => 'error', 'message' => 'يرجى إدخال اسم الميزان/الجهاز المراد معايرته.']);
            exit;
        }
        
        $variance = round($measuredValue - $referenceValue, 3);
        
        if (!empty($id)) {
            $stmtExist = $conn->prepare("SELECT * FROM calibrations WHERE id = ?");
            $stmtExist->bind_param('i', $id);
            $stmtExist->execute();
            $oldData = $stmtExist->get_result()->fetch_assoc();
            $stmtExist->close();
            
            if (!$oldData) {
                echo json_encode(['status' => 'error', 'message' => 'سجل المعايرة المطلوب غير موجود.']);
                exit;
            }
            
            $stmt = $conn->prepare("UPDATE calibrations SET 
                device_name = ?, device_code = ?, calibration_type = ?, reference_value = ?, measured_value = ?, variance = ?, unit = ?, status = ?, calibration_date = ?, next_calibration_date = ?, technician = ?, notes = ? WHERE id = ?");
                
            $stmt->bind_param('sssdddssssssi', $deviceName, $deviceCode, $calibrationType, $referenceValue, $measuredValue, $variance, $unit, $status, $calibrationDate, $nextCalibrationDate, $technician, $notes, $id);
            
            if ($stmt->execute()) {
                $stmt->close();
                logActivity($conn, 'update', 'calibrations', $id, $oldData, ['device_name' => $deviceName, 'status' => $status]);
                echo json_encode(['status' => 'success', 'message' => 'تم تحديث بيانات المعايرة بنجاح.']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'فشل التحديث: ' . $conn->error]);
            }
        } else {
            $stmt = $conn->prepare("INSERT INTO calibrations (device_name, device_code, calibration_type, reference_value, measured_value, variance, unit, status, calibration_date, next_calibration_date, technician, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param('sssdddssssss', $deviceName, $deviceCode, $calibrationType, $referenceValue, $measuredValue, $variance, $unit, $status, $calibrationDate, $nextCalibrationDate, $technician, $notes);
            
            if ($stmt->execute()) {
                $newId = $stmt->insert_id;
                $stmt->close();
                logActivity($conn, 'create', 'calibrations', $newId, null, ['device_name' => $deviceName, 'status' => $status]);
                echo json_encode(['status' => 'success', 'message' => 'تم حفظ بيانات المعايرة بنجاح.']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'فشل الإضافة: ' . $conn->error]);
            }
        }
        exit;
    }
    
    if ($action === 'delete') {
        checkApiPagePermission($pageKey, 'delete');
        $id = isset($input['id']) ? trim($input['id']) : '';
        if (empty($id)) {
            echo json_encode(['status' => 'error', 'message' => 'معرف السجل مطلوب للحذف.']);
            exit;
        }
        
        $stmtExist = $conn->prepare("SELECT * FROM calibrations WHERE id = ?");
        $stmtExist->bind_param('i', $id);
        $stmtExist->execute();
        $oldData = $stmtExist->get_result()->fetch_assoc();
        $stmtExist->close();
        
        if (!$oldData) {
            echo json_encode(['status' => 'error', 'message' => 'سجل المعايرة غير موجود.']);
            exit;
        }
        
        $stmt = $conn->prepare("DELETE FROM calibrations WHERE id = ?");
        $stmt->bind_param('i', $id);
        if ($stmt->execute()) {
            $stmt->close();
            logActivity($conn, 'delete', 'calibrations', $id, $oldData, null);
            echo json_encode(['status' => 'success', 'message' => 'تم حذف سجل المعايرة بنجاح.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'فشل الحذف: ' . $conn->error]);
        }
        exit;
    }
}
