<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';

// تأكد من وجود المعرف ونوع الحساب
if (!isset($_GET['id']) || !isset($_GET['type']) || empty($_GET['id']) || empty($_GET['type'])) {
    die('يرجى تحديد الحساب المطلوب');
}

$id = $_GET['id'];
$type = $_GET['type'];
$startDate = $_GET['start_date'] ?? date('Y-m-01'); // أول الشهر الحالي
$endDate = $_GET['end_date'] ?? date('Y-m-d'); // اليوم الحالي

// الحصول على اسم الحساب
$accountName = '';
if ($type === 'bank') {
    $stmt = $pdo->prepare("SELECT bank_name as name FROM bank_accounts WHERE id = ?");
} else {
    $stmt = $pdo->prepare("SELECT name FROM cash_funds WHERE id = ?");
}
$stmt->execute([$id]);
$result = $stmt->fetch();
$accountName = $result ? $result['name'] : 'غير معروف';

// حساب الرصيد الافتتاحي (قبل تاريخ البداية)
$openingBalance = 0;
$stmt = $pdo->prepare("
    SELECT 
        COALESCE(SUM(CASE 
            WHEN type IN ('deposit', 'transfer_in') THEN amount 
            ELSE -amount 
        END), 0) as balance
    FROM financial_transactions 
    WHERE account_type = ? 
    AND account_id = ? 
    AND transaction_date < ?
");
$stmt->execute([$type, $id, $startDate]);
$openingBalance = $stmt->fetchColumn();

// الحصول على المعاملات خلال الفترة المحددة
$stmt = $pdo->prepare("
    SELECT 
        ft.*,
        u.name as created_by,
        CASE 
            WHEN ft.type = 'transfer_out' THEN 
                CASE ft.transfer_to_type
                    WHEN 'bank' THEN (SELECT bank_name FROM bank_accounts WHERE id = ft.transfer_to_id)
                    WHEN 'cash' THEN (SELECT name FROM cash_funds WHERE id = ft.transfer_to_id)
                END
            WHEN ft.type = 'transfer_in' THEN 
                CASE 
                    WHEN EXISTS (SELECT 1 FROM financial_transactions ft2 WHERE ft2.type = 'transfer_out' AND ft2.transfer_to_type = ft.account_type AND ft2.transfer_to_id = ft.account_id AND ft2.amount = ft.amount AND ft2.transaction_date = ft.transaction_date) THEN
                        CASE (SELECT account_type FROM financial_transactions ft2 WHERE ft2.type = 'transfer_out' AND ft2.transfer_to_type = ft.account_type AND ft2.transfer_to_id = ft.account_id AND ft2.amount = ft.amount AND ft2.transaction_date = ft.transaction_date)
                            WHEN 'bank' THEN (SELECT bank_name FROM bank_accounts WHERE id = (SELECT account_id FROM financial_transactions ft2 WHERE ft2.type = 'transfer_out' AND ft2.transfer_to_type = ft.account_type AND ft2.transfer_to_id = ft.account_id AND ft2.amount = ft.amount AND ft2.transaction_date = ft.transaction_date))
                            WHEN 'cash' THEN (SELECT name FROM cash_funds WHERE id = (SELECT account_id FROM financial_transactions ft2 WHERE ft2.type = 'transfer_out' AND ft2.transfer_to_type = ft.account_type AND ft2.transfer_to_id = ft.account_id AND ft2.amount = ft.amount AND ft2.transaction_date = ft.transaction_date))
                        END
                END
        END as transfer_details
    FROM financial_transactions ft
    LEFT JOIN users u ON ft.created_by = u.id
    WHERE ft.account_type = ? 
    AND ft.account_id = ?
    AND ft.transaction_date BETWEEN ? AND ?
    ORDER BY ft.transaction_date ASC, ft.id ASC
");
$stmt->execute([$type, $id, $startDate, $endDate]);
$transactions = $stmt->fetchAll();

// حساب الرصيد الختامي
$currentBalance = $openingBalance;
foreach ($transactions as $transaction) {
    if (in_array($transaction['type'], ['deposit', 'transfer_in'])) {
        $currentBalance += $transaction['amount'];
    } else {
        $currentBalance -= $transaction['amount'];
    }
}
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>كشف حساب - <?php echo htmlspecialchars($accountName); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @media print {
            .no-print {
                display: none !important;
            }
            .table td, .table th {
                background-color: transparent !important;
            }
            body {
                padding: 0;
                margin: 0;
            }
            .container-fluid {
                width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            @page {
                size: A4;
                margin: 1cm;
            }
        }
        body {
            font-family: Arial, sans-serif;
        }
        .table th {
            background-color: #f8f9fa;
        }
        .text-success {
            color: #28a745 !important;
        }
        .text-danger {
            color: #dc3545 !important;
        }
        .print-header {
            border-bottom: 2px solid #000;
            margin-bottom: 20px;
            padding-bottom: 10px;
        }
        .print-footer {
            border-top: 1px solid #000;
            margin-top: 20px;
            padding-top: 10px;
            font-size: 0.8em;
        }
        .transaction-row:nth-child(even) {
            background-color: #f9f9f9;
        }
        .transaction-row td {
            padding: 8px !important;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <div class="print-header">
            <div class="row">
                <div class="col text-center">
                    <h2 class="mb-3">كشف حساب</h2>
                    <h4><?php echo htmlspecialchars($accountName); ?></h4>
                    <?php if ($startDate && $endDate): ?>
                    <p>الفترة: من <?php echo date('d/m/Y', strtotime($startDate)); ?> إلى <?php echo date('d/m/Y', strtotime($endDate)); ?></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h5>الرصيد الافتتاحي: <span class="<?php echo $openingBalance >= 0 ? 'text-success' : 'text-danger'; ?>">
                                    <?php echo number_format($openingBalance, 2); ?> درهم
                                </span></h5>
                            </div>
                            <div class="col-md-6 text-start">
                                <h5>الرصيد الختامي: <span class="<?php echo $currentBalance >= 0 ? 'text-success' : 'text-danger'; ?>">
                                    <?php echo number_format($currentBalance, 2); ?> درهم
                                </span></h5>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>التاريخ</th>
                        <th>نوع العملية</th>
                        <th>المبلغ</th>
                        <th>الوصف</th>
                        <th>المرجع</th>
                        <th>تفاصيل التحويل</th>
                        <th>المستخدم</th>
                        <th>الرصيد</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $runningBalance = $openingBalance;
                    foreach ($transactions as $transaction): 
                        $amount = $transaction['amount'];
                        if (in_array($transaction['type'], ['deposit', 'transfer_in'])) {
                            $runningBalance += $amount;
                        } else {
                            $runningBalance -= $amount;
                        }
                    ?>
                    <tr class="transaction-row">
                        <td><?php echo date('d/m/Y', strtotime($transaction['transaction_date'])); ?></td>
                        <td>
                            <?php
                            $type = $transaction['type'];
                            $typeText = '';
                            $typeClass = '';
                            
                            switch ($type) {
                                case 'deposit':
                                    $typeText = 'إيداع';
                                    $typeClass = 'text-success';
                                    break;
                                case 'withdrawal':
                                    $typeText = 'سحب';
                                    $typeClass = 'text-danger';
                                    break;
                                case 'transfer_out':
                                    $typeText = 'تحويل صادر';
                                    $typeClass = 'text-danger';
                                    break;
                                case 'transfer_in':
                                    $typeText = 'تحويل وارد';
                                    $typeClass = 'text-success';
                                    break;
                            }
                            ?>
                            <span class="<?php echo $typeClass; ?>"><?php echo $typeText; ?></span>
                        </td>
                        <td class="<?php echo in_array($type, ['deposit', 'transfer_in']) ? 'text-success' : 'text-danger'; ?>">
                            <?php echo number_format($transaction['amount'], 2); ?> درهم
                        </td>
                        <td><?php echo htmlspecialchars($transaction['description']); ?></td>
                        <td><?php echo htmlspecialchars($transaction['reference']); ?></td>
                        <td><?php echo htmlspecialchars($transaction['transfer_details'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($transaction['created_by']); ?></td>
                        <td class="<?php echo $runningBalance >= 0 ? 'text-success' : 'text-danger'; ?>">
                            <?php echo number_format($runningBalance, 2); ?> درهم
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="print-footer text-center">
            <p>تم إصدار هذا الكشف بتاريخ <?php echo date('d/m/Y H:i'); ?></p>
        </div>

        <div class="row mt-4 mb-4 no-print">
            <div class="col text-center">
                <button onclick="window.print()" class="btn btn-primary btn-lg">
                    <i class="bi bi-printer"></i> طباعة الكشف
                </button>
                <button onclick="window.close()" class="btn btn-secondary btn-lg">
                    <i class="bi bi-x"></i> إغلاق
                </button>
            </div>
        </div>
    </div>

    <script>
    // Automatically open print dialog when the page loads
    window.onload = function() {
        window.print();
    };
    </script>
</body>
</html>
