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

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

// Enforce view permission for gatherers report
checkApiPagePermission($pageKey, 'view');

// ================================================================
// shift_report — كشف الجلابين في الوردية الحالية
// ================================================================
// ================================================================
// shift_report — كشف الجلابين مع التصفية بالوردية والنطاق الزمني
// ================================================================
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET' && $action === 'shift_report') {

    // 1. --- حدود الوردية الافتراضية (ساعة البداية 5 صباحاً كميار قياسي) ---
    $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');
    }

    $mode = $_GET['mode'] ?? (isset($_GET['show_all']) && $_GET['show_all'] === 'true' ? 'previous' : 'current');

    // 2. --- بناء استعلام البيانات بحماية كاملة ومنع استبعاد أي مواد ---
    $where_clauses = ["f.status != 'cancelled'"];
    $params = [];
    $types  = "";

    if ($mode === 'current') {
        $where_clauses[] = "f.created_at >= ? AND f.created_at <= ?";
        $params[] = $shift_start;
        $params[] = $shift_end;
        $types   .= "ss";
    }

    if (!canViewOthersData()) {
        $myId = (int)$_SESSION['user']['id'];
        $where_clauses[] = "f.user_id = ?";
        $params[] = $myId;
        $types   .= "i";
    }

    $where_sql = implode(" AND ", $where_clauses);

    $query_str = "
        SELECT
            COALESCE(g.id, 0)               AS jallab_id,
            COALESCE(g.name, 'جلاب غير محدد') AS jallab_name,
            COALESCE(g.phone, '')           AS jallab_phone,
            fi.name                         AS material_name,
            fi.quantity,
            fi.weight,
            fi.price,
            fi.total,
            f.id                            AS form_id,
            f.customer_name,
            f.created_at                    AS form_date,
            COALESCE(m.accounting_type, '') AS accounting_type
        FROM form_items fi
        INNER JOIN forms f ON fi.form_id = f.id
        LEFT JOIN (
            SELECT m1.id, m1.name, m1.jallab_id, m1.accounting_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 TRIM(LOWER(fi.name)) = TRIM(LOWER(m.name))
        LEFT JOIN gatherers g ON m.jallab_id = g.id
        WHERE $where_sql
        ORDER BY jallab_name ASC, fi.name ASC, f.created_at DESC
    ";

    $st = $conn->prepare($query_str);
    if (!empty($params)) {
        $st->bind_param($types, ...$params);
    }
    $st->execute();
    $res = $st->get_result();
    $st->close();

    // 3. --- تجميع وتصنيف البيانات حسب الجلاب ---
    $gatherers = [];
    while ($row = $res->fetch_assoc()) {
        $jid      = (int)$row['jallab_id'];
        $jname    = $row['jallab_name'];
        $qty      = (int)$row['quantity'];
        $weight   = (float)($row['weight'] ?? 0);
        $price    = (float)$row['price'];
        $acc_type = $row['accounting_type'] ?? '';

        // حساب الإجمالي الصافي (وزن×سعر أو عدد×سعر)
        $subtotal = ($acc_type === 'وزن * سعر' && $weight > 0) ? ($weight * $price) : ($qty * $price);
        if ($subtotal <= 0 && (float)$row['total'] > 0) {
            $subtotal = (float)$row['total'];
        }

        if (!isset($gatherers[$jid])) {
            $gatherers[$jid] = [
                'id'              => $jid,
                'name'            => $jname,
                'phone'           => $row['jallab_phone'],
                'customer_set'    => [],
                'total_qty'       => 0,
                'total_weight'    => 0.0,
                'total_revenue'   => 0.0,
                'items'           => []
            ];
        }

        $gatherers[$jid]['customer_set'][$row['customer_name']] = true;
        $gatherers[$jid]['total_qty']     += $qty;
        $gatherers[$jid]['total_weight']  += $weight;
        $gatherers[$jid]['total_revenue'] += $subtotal;

        $gatherers[$jid]['items'][] = [
            'form_id'         => (int)$row['form_id'],
            'customer_name'   => $row['customer_name'],
            'material_name'   => $row['material_name'],
            'quantity'        => $qty,
            'weight'          => $row['weight'] !== null ? $weight : null,
            'price'           => $price,
            'subtotal'        => round($subtotal, 2),
            'accounting_type' => $acc_type,
            'total'           => (float)$row['total'],
            'form_date'       => $row['form_date']
        ];
    }

    // بناء المصفوفة النهائية وحساب النسب الإحصائية
    $list = [];
    $grand_qty     = 0;
    $grand_weight  = 0.0;
    $grand_revenue = 0.0;

    foreach ($gatherers as $g) {
        $grand_qty     += $g['total_qty'];
        $grand_weight  += $g['total_weight'];
        $grand_revenue += $g['total_revenue'];
    }

    foreach ($gatherers as &$g) {
        $g['customer_count'] = count($g['customer_set']);
        unset($g['customer_set']);
        $g['total_weight']  = round($g['total_weight'], 2);
        $g['total_revenue'] = round($g['total_revenue'], 2);
        $g['revenue_percentage'] = $grand_revenue > 0 ? round(($g['total_revenue'] / $grand_revenue) * 100, 1) : 0;
        $g['avg_unit_price'] = $g['total_qty'] > 0 ? round($g['total_revenue'] / $g['total_qty'], 2) : 0;
        $list[] = $g;
    }
    unset($g);

    echo json_encode([
        'status'      => 'success',
        'mode'        => $mode,
        'shift_start' => $shift_start,
        'shift_end'   => $shift_end,
        'gatherers'   => $list,
        'summary'     => [
            'total_gatherers' => count($list),
            'grand_qty'       => $grand_qty,
            'grand_weight'    => round($grand_weight, 2),
            'grand_revenue'   => round($grand_revenue, 2)
        ]
    ]);
    exit;
}

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