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

// Enforce permission checks
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    checkApiPagePermission($pageKey, 'view');
} elseif (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    checkApiPagePermission($pageKey, 'edit');
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    if ($action === 'list_gatherers') {
        $result = $conn->query("SELECT id, name, phone FROM gatherers ORDER BY name ASC");
        $gatherers = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $gatherers[] = $row;
            }
        }
        echo json_encode(['status' => 'success', 'gatherers' => $gatherers]);
        exit;
    }

    if ($action === 'list_safes') {
        $result = $conn->query("SELECT id, name FROM safes ORDER BY id ASC");
        $safes = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $safes[] = $row;
            }
        }
        echo json_encode(['status' => 'success', 'safes' => $safes]);
        exit;
    }

    if ($action === 'get_settlement') {
        $jallab_id = isset($_GET['jallab_id']) ? intval($_GET['jallab_id']) : 0;
        if (!$jallab_id) {
            echo json_encode(['status' => 'error', 'message' => 'الرجاء اختيار جلاب صالح']);
            exit;
        }

        $show_all = isset($_GET['show_all']) && $_GET['show_all'] === 'true';

        // --- boundaries of current shift ---
        $sr = $conn->query("SELECT workday_start_hour FROM system_settings WHERE id = 1");
        $start_hour = 17;
        if ($sr && $row = $sr->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');
        }

        // Query all priced/approved form items for this gatherer (strictly excluding cancelled)
        $query_str = "
            SELECT
                fi.name AS material_name,
                fi.quantity,
                fi.weight,
                fi.price,
                fi.total,
                f.id AS form_id,
                f.customer_name,
                m.accounting_type
            FROM form_items fi
            INNER JOIN forms f ON fi.form_id = f.id
            INNER JOIN materials m ON m.id = (
                SELECT MAX(m2.id) FROM materials m2
                WHERE TRIM(LOWER(m2.name)) = TRIM(LOWER(fi.name))
            )
            WHERE m.jallab_id = ?
              AND f.status != 'cancelled'
              AND (f.status IN ('1', '2', '3', 'approved'))
        ";

        $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
        $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';

        $from_dt = '';
        $to_dt = '';
        if ($start_date && $end_date) {
            $from_dt = $start_date . ' 00:00:00';
            $to_dt   = $end_date . ' 23:59:59';
            $query_str .= " AND f.created_at >= ? AND f.created_at <= ? ";
        } else if (!$show_all) {
            $query_str .= " AND f.created_at >= ? AND f.created_at < ? ";
        }
        $query_str .= " ORDER BY fi.name ASC ";

        $st = $conn->prepare($query_str);
        if ($start_date && $end_date) {
            $st->bind_param('iss', $jallab_id, $from_dt, $to_dt);
        } else if (!$show_all) {
            $st->bind_param('iss', $jallab_id, $shift_start, $shift_end);
        } else {
            $st->bind_param('i', $jallab_id);
        }
        $st->execute();
        $res = $st->get_result();
        $st->close();

        // Group by material name
        $grouped = [];
        while ($row = $res->fetch_assoc()) {
            $name = $row['material_name'];
            $qty = (int)$row['quantity'];
            $weight = $row['weight'] !== null ? (float)$row['weight'] : 0.0;
            $price = (float)$row['price'];
            $acc_type = $row['accounting_type'] ?? 'عدد * سعر';

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

            if (!isset($grouped[$name])) {
                $grouped[$name] = [
                    'name' => $name,
                    'accounting_type' => $acc_type,
                    'total_qty' => 0,
                    'total_weight' => 0.0,
                    'total_amount' => 0.0
                ];
            }

            $grouped[$name]['total_qty'] += $qty;
            $grouped[$name]['total_weight'] += $weight;
            $grouped[$name]['total_amount'] += $subtotal;
        }

        $table1 = []; // Count-based: ت - اسم المادة - العدد - معدل السعر - المبلغ
        $table2 = []; // Weight-based: ت - اسم المادة - العدد - الوزن - معدل السعر - المبلغ

        foreach ($grouped as $name => $g) {
            $avg_price = 0.0;
            if ($g['accounting_type'] === 'وزن * سعر') {
                if ($g['total_weight'] > 0) {
                    $avg_price = $g['total_amount'] / $g['total_weight'];
                }
                $table2[] = [
                    'material_name' => $g['name'],
                    'total_qty' => $g['total_qty'],
                    'total_weight' => round($g['total_weight'], 2),
                    'avg_price' => round($avg_price, 2),
                    'total_amount' => round($g['total_amount'], 2)
                ];
            } else {
                if ($g['total_qty'] > 0) {
                    $avg_price = $g['total_amount'] / $g['total_qty'];
                }
                $table1[] = [
                    'material_name' => $g['name'],
                    'total_qty' => $g['total_qty'],
                    'avg_price' => round($avg_price, 2),
                    'total_amount' => round($g['total_amount'], 2)
                ];
            }
        }

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

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

    if ($action === 'pay_settlement') {
        $jallab_id = isset($input['jallab_id']) ? intval($input['jallab_id']) : 0;
        $safe_id   = isset($input['safe_id']) ? intval($input['safe_id']) : 0;
        $amount    = isset($input['amount']) ? floatval($input['amount']) : 0.0;
        $notes     = isset($input['notes']) ? trim($input['notes']) : '';

        if (!$jallab_id || !$safe_id || $amount <= 0) {
            echo json_encode(["status" => "error", "message" => "يرجى تحديد الجلاب والقاصة وإدخال مبلغ تسوية صحيح!"]);
            exit;
        }

        // Fetch gatherer name
        $stmt_g = $conn->prepare("SELECT name FROM gatherers WHERE id = ?");
        $stmt_g->bind_param("i", $jallab_id);
        $stmt_g->execute();
        $g_res = $stmt_g->get_result()->fetch_assoc();
        $stmt_g->close();

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

        // Check safe balance before withdrawal
        $stmt_s = $conn->prepare("
            SELECT name,
                COALESCE(SUM(CASE WHEN type = 'deposit' THEN amount WHEN type = 'withdrawal' THEN -amount ELSE 0 END), 0) AS balance
            FROM safes
            LEFT JOIN safe_transactions ON safes.id = safe_transactions.safe_id
            WHERE safes.id = ?
            GROUP BY safes.id
        ");
        $stmt_s->bind_param("i", $safe_id);
        $stmt_s->execute();
        $safe_data = $stmt_s->get_result()->fetch_assoc();
        $stmt_s->close();

        if (!$safe_data) {
            echo json_encode(["status" => "error", "message" => "القاصة المحددة غير موجودة"]);
            exit;
        }

        if ($safe_data['balance'] < $amount) {
            echo json_encode(["status" => "error", "message" => "رصيد القاصة الحالي (" . number_format($safe_data['balance']) . " د.ع) غير كافٍ لسحب مبلغ التسوية (" . number_format($amount) . " د.ع)!"]);
            exit;
        }

        $description = "صرف تسوية مستحقات مالية للجلاب: " . $g_res['name'] . ($notes ? " ($notes)" : "");
        $user_id = $_SESSION['user']['id'] ?? 1;

        $stmt_tx = $conn->prepare("INSERT INTO safe_transactions (safe_id, type, amount, description, user_id, created_at) VALUES (?, 'withdrawal', ?, ?, ?, NOW())");
        $stmt_tx->bind_param("idsi", $safe_id, $amount, $description, $user_id);
        if ($stmt_tx->execute()) {
            $tx_id = $conn->insert_id;
            logActivity($conn, 'insert', 'safe_transactions', $tx_id, null, [
                'safe_id' => $safe_id,
                'type' => 'withdrawal',
                'amount' => $amount,
                'description' => $description
            ]);
            logActivity($conn, 'update', 'settlements', $jallab_id, null, [
                'action' => 'payout',
                'jallab_name' => $g_res['name'],
                'amount' => $amount,
                'safe_name' => $safe_data['name']
            ]);
            updateSystemState($conn, 'safes');
            echo json_encode(["status" => "success", "message" => "تم صرف وتسديد تسوية الجلاب بنجاح وقيد حركة السحب في القاصة!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "فشل قيد عملية السحب في القاصة"]);
        }
        $stmt_tx->close();
        exit;
    }
}

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