<?php
/**
 * Shift Summary API
 * يحسب ملخص الشفت من الفواتير الفعلية + حركات الدرج النقدي
 * مصدر حقيقة واحد — بدلاً من التضارب بين جدول shifts والفواتير
 */

require_once __DIR__ . '/auth.php';

// التحقق من التوكن
$token = getBearerToken();
if (empty($token)) {
    jsonResponse(false, 'Unauthorized', null, 401);
}

$decoded = verifyToken($token);
if (!$decoded) {
    jsonResponse(false, 'Invalid token', null, 401);
}

// استقبال المعاملات
$shiftId = $_GET['shift_id'] ?? '';
$sellerId = $_GET['seller_id'] ?? '';

if (empty($shiftId) || empty($sellerId)) {
    jsonResponse(false, 'shift_id and seller_id are required', null, 400);
}

try {
    global $pdo;
    
    // 1) جلب بيانات الشفت الأساسية
    $stmtShift = $pdo->prepare("SELECT * FROM shifts WHERE id = ? AND seller_id = ? LIMIT 1");
    $stmtShift->execute([$shiftId, $sellerId]);
    $shiftRow = $stmtShift->fetch(PDO::FETCH_ASSOC);
    
    if (!$shiftRow) {
        jsonResponse(false, 'Shift not found', null, 404);
    }
    
    // 2) حساب المبيعات من الفواتير الفعلية
    $stmtInvoices = $pdo->prepare("
        SELECT 
            payment_method,
            total_amount,
            is_return
        FROM invoices 
        WHERE shift_id = ? 
          AND seller_id = ?
          AND (is_hidden = 0 OR is_hidden IS NULL)
          AND status != 'ملغية' 
          AND status != 'cancelled'
    ");
    $stmtInvoices->execute([$shiftId, $sellerId]);
    $invoices = $stmtInvoices->fetchAll(PDO::FETCH_ASSOC);
    
    $totalSales = 0;
    $totalInvoices = 0;
    $totalCashSales = 0;
    $totalCardSales = 0;
    $totalCreditSales = 0;
    $breakdownMap = [];
    
    foreach ($invoices as $inv) {
        $rawAmount = floatval($inv['total_amount'] ?? 0);
        $isReturn = ($inv['is_return'] == 1 || $inv['is_return'] === true || $inv['is_return'] === '1');
        $amount = $isReturn ? -$rawAmount : $rawAmount;
        
        $paymentText = strtolower(trim($inv['payment_method'] ?? ''));
        
        $methodCode = 'other';
        $methodName = $inv['payment_method'] ?: 'غير محدد';
        $affectsCash = false;
        
        if ($paymentText === 'نقدي' || $paymentText === 'cash' || strpos($paymentText, 'نقد') !== false) {
            $methodCode = 'cash'; $methodName = 'نقدي'; $affectsCash = true;
        } elseif (strpos($paymentText, 'بطاقة') !== false || $paymentText === 'card' || strpos($paymentText, 'ائتمان') !== false || strpos($paymentText, 'visa') !== false) {
            $methodCode = 'card'; $methodName = 'بطاقة ائتمان'; $affectsCash = false;
        } elseif (strpos($paymentText, 'آجل') !== false || $paymentText === 'credit' || strpos($paymentText, 'ذمم') !== false || strpos($paymentText, 'دين') !== false) {
            $methodCode = 'credit'; $methodName = 'آجل (ذمم)'; $affectsCash = false;
        } elseif (strpos($paymentText, 'cliq') !== false || strpos($paymentText, 'كليك') !== false) {
            $methodCode = 'cliq'; $methodName = 'كليك (CliQ)'; $affectsCash = false;
        } elseif (strpos($paymentText, 'تحويل') !== false || strpos($paymentText, 'بنك') !== false || strpos($paymentText, 'bank') !== false) {
            $methodCode = 'bank_transfer'; $methodName = 'تحويل بنكي'; $affectsCash = false;
        }
        
        $totalSales += $amount;
        $totalInvoices++;
        
        if ($affectsCash) {
            $totalCashSales += $amount;
        } elseif ($methodCode === 'card') {
            $totalCardSales += $amount;
        } elseif ($methodCode === 'credit') {
            $totalCreditSales += $amount;
        }
        
        if (!isset($breakdownMap[$methodCode])) {
            $breakdownMap[$methodCode] = [
                'method_code' => $methodCode,
                'method_name' => $methodName,
                'total_amount' => 0,
                'invoice_count' => 0,
                'affects_cash_drawer' => $affectsCash
            ];
        }
        $breakdownMap[$methodCode]['total_amount'] += $amount;
        $breakdownMap[$methodCode]['invoice_count']++;
    }
    
    // 3) حساب الإيداعات والسحوبات
    $stmtCash = $pdo->prepare("
        SELECT transaction_type, amount 
        FROM cash_drawer_transactions 
        WHERE shift_id = ? AND seller_id = ?
    ");
    $stmtCash->execute([$shiftId, $sellerId]);
    $cashTxns = $stmtCash->fetchAll(PDO::FETCH_ASSOC);
    
    $cashDeposits = 0;
    $cashWithdrawals = 0;
    
    foreach ($cashTxns as $tx) {
        $txAmount = floatval($tx['amount'] ?? 0);
        $txType = $tx['transaction_type'] ?? '';
        
        if ($txType === 'deposit' || $txType === 'cash_in') {
            $cashDeposits += $txAmount;
        } elseif ($txType === 'withdrawal' || $txType === 'cash_out') {
            $cashWithdrawals += $txAmount;
        }
    }
    
    // 4) حساب المتوقع في الدرج
    $openingCash = floatval($shiftRow['opening_cash'] ?? 0);
    $expectedCash = $openingCash + $totalCashSales + $cashDeposits - $cashWithdrawals;
    
    // 5) إرجاع الملخص الموحد
    jsonResponse(true, 'Shift summary loaded', [
        'shift' => $shiftRow,
        'summary' => [
            'total_sales' => round($totalSales, 3),
            'total_invoices' => $totalInvoices,
            'total_cash_sales' => round($totalCashSales, 3),
            'total_card_sales' => round($totalCardSales, 3),
            'total_credit_sales' => round($totalCreditSales, 3),
            'opening_cash' => $openingCash,
            'cash_deposits' => round($cashDeposits, 3),
            'cash_withdrawals' => round($cashWithdrawals, 3),
            'expected_cash' => round($expectedCash, 3),
            'payment_breakdown' => array_values($breakdownMap)
        ]
    ]);

} catch (Exception $e) {
    jsonResponse(false, 'Server error: ' . $e->getMessage(), null, 500);
}
