<?php
// إخفاء شريط التنقل لهذه الصفحة
define('HIDE_NAVBAR', true);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';

// تهيئة قاعدة البيانات والمصادقة
$database = new Database();
$pdo = $database->getConnection();
$auth = new Auth($database);

// التحقق من تسجيل الدخول والصلاحيات
if (!$auth->isLoggedIn() || !$auth->hasPermission('treasurer')) {
    header('Location: index.php?page=login');
    exit;
}

// التحقق من وجود المعرف ونوع الحساب
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');

// الحصول على معلومات الحساب والرصيد الحالي
if ($type === 'bank') {
    $stmt = $pdo->prepare("SELECT bank_name as name, current_balance FROM bank_accounts WHERE id = ?");
} else {
    $stmt = $pdo->prepare("SELECT name, current_balance FROM cash_funds WHERE id = ?");
}
$stmt->execute([$id]);
$accountInfo = $stmt->fetch();
$accountName = $accountInfo ? $accountInfo['name'] : 'غير معروف';
$currentBalance = $accountInfo ? $accountInfo['current_balance'] : 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.username as created_by_name,
        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();

// حساب الرصيد الختامي للفترة المحددة
$periodBalance = $openingBalance;
foreach ($transactions as $transaction) {
    if (in_array($transaction['type'], ['deposit', 'transfer_in'])) {
        $periodBalance += $transaction['amount'];
    } else {
        $periodBalance -= $transaction['amount'];
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<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 {
            @page {
                size: A4;
                margin: 1.5cm;
            }
            body {
                font-size: 12pt;
                line-height: 1.3;
                background: none;
                margin: 0;
                padding: 0;
            }
            .no-print, .no-print * {
                display: none !important;
            }
            #wrapper, #content {
                margin: 0 !important;
                padding: 0 !important;
            }
            .navbar, .sidebar, #sidebarCollapse {
                display: none !important;
            }
            .page-header {
                margin-bottom: 20px;
                border-bottom: 1px solid #000;
                padding-bottom: 10px;
            }
            table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 20px;
                page-break-inside: auto;
            }
            tr {
                page-break-inside: avoid;
                page-break-after: auto;
            }
            th, td {
                padding: 8px;
                border: 1px solid #000;
            }
            th {
                background-color: #f8f9fa !important;
                font-weight: bold;
            }
            .table-striped tbody tr:nth-of-type(odd) {
                background-color: #f8f9fa !important;
            }
            .container-fluid {
                padding: 0 !important;
                margin: 0 !important;
            }
        }
        body {
            font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", "Liberation Sans", Arial, sans-serif;
            line-height: 1.6;
            padding: 20px;
        }
        .positive {
            color: #198754 !important;
            font-weight: bold;
        }
        .negative {
            color: #dc3545 !important;
            font-weight: bold;
        }
        .amount {
            text-align: left;
        }
        .print-button {
            position: fixed;
            bottom: 20px;
            left: 20px;
            z-index: 1000;
        }
        .balance-info {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .balance-info .row {
            margin-bottom: 10px;
        }
        .balance-info .label {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <!-- رأس الصفحة -->
        <div class="page-header text-center">
            <h1 class="mb-3">كشف حساب</h1>
            <h3 class="mb-3"><?php echo htmlspecialchars($accountName); ?></h3>
            <p class="mb-4">الفترة: من <?php echo date('d/m/Y', strtotime($startDate)); ?> إلى <?php echo date('d/m/Y', strtotime($endDate)); ?></p>
        </div>

        <!-- معلومات الأرصدة -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <strong>الرصيد الافتتاحي:</strong>
                        <span class="<?php echo $openingBalance >= 0 ? 'positive' : 'negative'; ?>">
                            <?php echo number_format($openingBalance, 2); ?> درهم
                        </span>
                    </div>
                    <div class="col-md-4">
                        <strong>رصيد الفترة:</strong>
                        <span class="<?php echo $periodBalance >= 0 ? 'positive' : 'negative'; ?>">
                            <?php echo number_format($periodBalance, 2); ?> درهم
                        </span>
                    </div>
                    <div class="col-md-4">
                        <strong>الرصيد الحالي:</strong>
                        <span class="<?php echo $currentBalance >= 0 ? 'positive' : 'negative'; ?>">
                            <?php echo number_format($currentBalance, 2); ?> درهم
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- جدول المعاملات -->
        <div class="table-responsive">
            <table class="table table-striped table-bordered">
                <thead class="table-light">
                    <tr>
                        <th>التاريخ</th>
                        <th>نوع العملية</th>
                        <th>المبلغ</th>
                        <th>الوصف</th>
                        <th>المرجع</th>
                        <th>تفاصيل التحويل</th>
                        <th>الرصيد</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $runningBalance = $openingBalance;
                    foreach ($transactions as $transaction): 
                        if (in_array($transaction['type'], ['deposit', 'transfer_in'])) {
                            $runningBalance += $transaction['amount'];
                            $amountClass = 'positive';
                            $typeText = $transaction['type'] === 'deposit' ? 'إيداع' : 'تحويل وارد';
                        } else {
                            $runningBalance -= $transaction['amount'];
                            $amountClass = 'negative';
                            $typeText = $transaction['type'] === 'withdrawal' ? 'سحب' : 'تحويل صادر';
                        }
                    ?>
                    <tr>
                        <td><?php echo date('d/m/Y', strtotime($transaction['transaction_date'])); ?></td>
                        <td><?php echo $typeText; ?></td>
                        <td class="amount <?php echo $amountClass; ?>"><?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 class="amount <?php echo $runningBalance >= 0 ? 'positive' : 'negative'; ?>">
                            <?php echo number_format($runningBalance, 2); ?> درهم
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

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

        <!-- زر الطباعة -->
        <div class="print-button no-print">
            <button onclick="window.print()" class="btn btn-primary">
                <i class="fas fa-print"></i> طباعة الكشف
            </button>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // طباعة تلقائية عند تحميل الصفحة
        window.onload = function() {
            window.print();
        };
    </script>
</body>
</html>
