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

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

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

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

    // ============================================================
    // shift_report — كشف مواد الوردية الحالية
    // ============================================================
    if ($action === 'shift_report') {

        // --- حساب حدود الوردية ---
        $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');
        }

        $shift_start_ts = (new DateTime($shift_start, new DateTimeZone('Asia/Baghdad')))->getTimestamp();
        $shift_end_ts   = (new DateTime($shift_end,   new DateTimeZone('Asia/Baghdad')))->getTimestamp();

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

        $where_clauses = ["f.status != 'cancelled'"];
        $params = [];
        $types  = "";

        if (!$show_all) {
            $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
                fi.id          AS item_id,
                fi.name        AS material_name,
                fi.quantity,
                fi.weight,
                fi.price,
                fi.total,
                fi.worker_share,
                fi.commission,
                fi.commission_10,
                f.id           AS form_id,
                f.customer_name,
                f.status       AS form_status,
                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 TRIM(LOWER(name)) AS norm_name, MAX(accounting_type) AS accounting_type
                FROM materials
                GROUP BY TRIM(LOWER(name))
            ) m ON TRIM(LOWER(fi.name)) = m.norm_name
            WHERE $where_sql
            ORDER BY 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();

        // --- تجميع المواد المباعة في الاستمارات (نقداً أو دين) للوردية الحالية ---
        $materials = [];

        while ($row = $res->fetch_assoc()) {
            $name     = trim($row['material_name']);
            if (empty($name)) continue;
            $qty      = (int)$row['quantity'];
            $weight   = (float)($row['weight'] ?? 0);
            $price    = (float)$row['price'];
            $acc_type = !empty($row['accounting_type']) ? $row['accounting_type'] : '';

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

            if (!isset($materials[$name])) {
                $materials[$name] = [
                    'name'            => $name,
                    'accounting_type' => $acc_type,
                    'total_qty'       => 0,
                    'total_weight'    => 0.0,
                    'total_revenue'   => 0.0,
                    'total_worker'    => 0.0,
                    'total_comm'      => 0.0,
                    'total_comm10'    => 0.0,
                    'transactions'    => []
                ];
            }
            if (!empty($acc_type)) {
                $materials[$name]['accounting_type'] = $acc_type;
            }
            $materials[$name]['total_qty']     += $qty;
            $materials[$name]['total_weight']  += $weight;
            $materials[$name]['total_revenue'] += $subtotal;
            $materials[$name]['total_worker']  += (float)$row['worker_share'];
            $materials[$name]['total_comm']    += (float)$row['commission'];
            $materials[$name]['total_comm10']  += (float)$row['commission_10'];
            $materials[$name]['transactions'][] = [
                'item_id'         => (int)$row['item_id'],
                'form_id'         => (int)$row['form_id'],
                'customer_name'   => $row['customer_name'],
                'form_status'     => $row['form_status'],
                'quantity'        => $qty,
                'weight'          => $row['weight'] !== null ? $weight : null,
                'price'           => $price,
                'subtotal'        => round($subtotal, 2),
                'accounting_type' => $acc_type,
                'total'           => (float)$row['total'],
                'worker_share'    => (float)$row['worker_share'],
                'commission'      => (float)$row['commission'],
                'commission_10'   => (float)$row['commission_10'],
                'form_date'       => $row['form_date']
            ];
        }

        // --- إحصائيات إجمالية وحساب النسب ---
        $all = array_values($materials);
        $grand_qty     = array_sum(array_column($all, 'total_qty'));
        $grand_weight  = array_sum(array_column($all, 'total_weight'));
        $grand_revenue = array_sum(array_column($all, 'total_revenue'));
        $grand_worker  = array_sum(array_column($all, 'total_worker'));
        $grand_comm10  = array_sum(array_column($all, 'total_comm10'));

        foreach ($all as &$m) {
            $m['total_weight']  = round($m['total_weight'], 2);
            $m['total_revenue'] = round($m['total_revenue'], 2);
            $m['total_worker']  = round($m['total_worker'], 2);
            $m['total_comm10']  = round($m['total_comm10'], 2);
            $m['revenue_percentage'] = $grand_revenue > 0 ? round(($m['total_revenue'] / $grand_revenue) * 100, 1) : 0;
            $m['avg_unit_price'] = $m['total_qty'] > 0 ? round($m['total_revenue'] / $m['total_qty'], 2) : 0;
        }
        unset($m);

        echo json_encode([
            'status'          => 'success',
            'shift_start'     => $shift_start,
            'shift_end'       => $shift_end,
            'shift_start_ts'  => $shift_start_ts,
            'shift_end_ts'    => $shift_end_ts,
            'materials'       => $all,
            'summary'         => [
                'total_materials' => count($all),
                'grand_qty'       => $grand_qty,
                'grand_weight'    => round($grand_weight, 2),
                'grand_revenue'   => round($grand_revenue, 2),
                'grand_worker'    => round($grand_worker, 2),
                'grand_comm10'    => round($grand_comm10, 2)
            ]
        ]);
        exit;
    }
}

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