<?php
session_start();
ob_start();

// Debug mode - set to false for production
define('DEBUG', false);

if (!isset($_SESSION['member_id'])) {
    header("Location: login.php");
    exit;
}

require_once './includes/config.php';
require_once './auth/middleware.php';
outputSessionTimeoutWarning();

try {
    // Fetch member details
    $stmt = $pdo->prepare("
        SELECT id, first_name, last_name, member_number 
        FROM members 
        WHERE id = ?
    ");
    $stmt->execute([$_SESSION['member_id']]);
    $member = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$member) {
        throw new Exception("No member found with ID: " . $_SESSION['member_id']);
    }

    // Handle statement period selection
    $defaultStart = date('Y-m-01');
    $defaultEnd = date('Y-m-t');
    
    $startDate = $_GET['start_date'] ?? $defaultStart;
    $endDate = $_GET['end_date'] ?? $defaultEnd;
    $accountId = $_GET['account_id'] ?? null;

    // Validate dates
    if (!strtotime($startDate) || !strtotime($endDate)) {
        $startDate = $defaultStart;
        $endDate = $defaultEnd;
    }

    // Fetch member accounts for dropdown
    $accountsStmt = $pdo->prepare("
        SELECT ma.id, ma.account_number, at.account_name 
        FROM member_accounts ma
        JOIN account_types at ON ma.account_type_id = at.id
        WHERE ma.member_id = ?
        ORDER BY at.account_name
    ");
    $accountsStmt->execute([$_SESSION['member_id']]);
    $accounts = $accountsStmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch transactions if account is selected
    $transactions = [];
    $accountDetails = null;
    $openingBalance = 0;
    $closingBalance = 0;

    if ($accountId) {
        // Validate account belongs to member
        $validAccount = false;
        foreach ($accounts as $account) {
            if ($account['id'] == $accountId) {
                $validAccount = true;
                $accountDetails = $account;
                break;
            }
        }

        if ($validAccount) {
            // Get opening balance (balance before start date)
            $openingStmt = $pdo->prepare("
                SELECT balance 
                FROM account_balances 
                WHERE account_id = ? AND date < ? 
                ORDER BY date DESC 
                LIMIT 1
            ");
            $openingStmt->execute([$accountId, $startDate]);
            $openingBalance = $openingStmt->fetchColumn() ?? 0;

            // Fetch transactions
            $transactionsStmt = $pdo->prepare("
                SELECT 
                    t.id, t.transaction_date, t.description,
                    t.amount, t.transaction_type, t.reference_number,
                    t.balance_after, t.created_at,
                    tt.name AS transaction_type_name,
                    tt.is_credit
                FROM transactions t
                JOIN transaction_types tt ON t.transaction_type_id = tt.id
                WHERE t.member_id = ? AND t.account_id = ?
                AND t.transaction_date BETWEEN ? AND ?
                ORDER BY t.transaction_date DESC, t.id DESC
            ");
            $transactionsStmt->execute([
                $_SESSION['member_id'],
                $accountId,
                $startDate,
                $endDate
            ]);
            $transactions = $transactionsStmt->fetchAll(PDO::FETCH_ASSOC);

            // Get closing balance (last transaction balance or opening if no transactions)
            if (!empty($transactions)) {
                $closingBalance = $transactions[0]['balance_after'];
            } else {
                // If no transactions, check if we have a balance record
                $closingStmt = $pdo->prepare("
                    SELECT balance 
                    FROM account_balances 
                    WHERE account_id = ? AND date <= ? 
                    ORDER BY date DESC 
                    LIMIT 1
                ");
                $closingStmt->execute([$accountId, $endDate]);
                $closingBalance = $closingStmt->fetchColumn() ?? $openingBalance;
            }
        }
    }

    // Fetch company details for statement header
    $companyStmt = $pdo->query("SELECT * FROM company_settings LIMIT 1");
    $company = $companyStmt->fetch(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}

$companyName = htmlspecialchars($company['company_name'] ?? 'Financial Institution');
$title = 'Account Statement';
$subTitle = 'Statement for ' . htmlspecialchars($member['first_name'] . ' ' . $member['last_name']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $title; ?> | <?php echo $companyName; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3a0ca3;
            --accent-color: #f72585;
            --success-color: #4cc9f0;
            --warning-color: #f8961e;
            --danger-color: #ef233c;
            --light-bg: #f8f9fa;
            --dark-color: #212529;
            --gray-color: #6c757d;
            --border-radius: 8px;
            --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background-color: var(--light-bg);
            color: var(--dark-color);
        }
        
        .statement-container {
            background-color: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: 2rem;
        }
        
        .statement-header {
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .statement-title {
            color: var(--secondary-color);
            font-weight: 700;
        }
        
        .statement-period {
            background-color: var(--primary-light);
            padding: 1rem;
            border-radius: var(--border-radius);
            margin-bottom: 1.5rem;
        }
        
        .transaction-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .transaction-table th {
            background-color: var(--primary-color);
            color: white;
            padding: 12px 15px;
            text-align: left;
        }
        
        .transaction-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
        }
        
        .transaction-table tr:last-child td {
            border-bottom: none;
        }
        
        .transaction-table tr:hover {
            background-color: rgba(67, 97, 238, 0.05);
        }
        
        .credit-amount {
            color: #28a745;
            font-weight: 600;
        }
        
        .debit-amount {
            color: var(--danger-color);
            font-weight: 600;
        }
        
        .summary-card {
            background-color: var(--light-bg);
            border-radius: var(--border-radius);
            padding: 1.5rem;
            margin-top: 2rem;
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }
        
        .summary-item:last-child {
            border-bottom: none;
            font-weight: 700;
            font-size: 1.1rem;
        }
        
        .print-btn {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .print-btn:hover {
            background-color: var(--secondary-color);
            transform: translateY(-2px);
        }
        
        @media print {
            body * {
                visibility: hidden;
            }
            .statement-container, .statement-container * {
                visibility: visible;
            }
            .statement-container {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                box-shadow: none;
            }
            .no-print {
                display: none !important;
            }
        }
        
        .date-picker {
            max-width: 200px;
            display: inline-block;
        }
        
        .account-select {
            min-width: 250px;
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="statement-container">
            <!-- Statement Header -->
            <div class="statement-header">
                <div class="row">
                    <div class="col-md-6">
                        <h1 class="statement-title">Account Statement</h1>
                        <?php if ($accountDetails): ?>
                            <h5><?php echo htmlspecialchars($accountDetails['account_name']); ?></h5>
                            <p class="text-muted">Account #: <?php echo htmlspecialchars($accountDetails['account_number']); ?></p>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-6 text-end">
                        <img src="<?php echo htmlspecialchars($company['logo_url'] ?? ''); ?>" alt="<?php echo $companyName; ?>" style="max-height: 60px;" class="mb-3">
                        <p class="mb-1"><?php echo $companyName; ?></p>
                        <p class="text-muted small"><?php echo htmlspecialchars($company['address'] ?? ''); ?></p>
                    </div>
                </div>
            </div>
            
            <!-- Statement Filters -->
            <div class="no-print">
                <form method="get" class="mb-4">
                    <div class="row g-3 align-items-end">
                        <div class="col-md-4">
                            <label for="account_id" class="form-label">Account</label>
                            <select name="account_id" id="account_id" class="form-select account-select" required>
                                <option value="">Select Account</option>
                                <?php foreach ($accounts as $account): ?>
                                    <option value="<?php echo $account['id']; ?>" <?php echo $accountId == $account['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($account['account_name'] . ' (' . $account['account_number'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="start_date" class="form-label">From Date</label>
                            <input type="date" name="start_date" id="start_date" 
                                   class="form-control date-picker" 
                                   value="<?php echo htmlspecialchars($startDate); ?>" required>
                        </div>
                        <div class="col-md-3">
                            <label for="end_date" class="form-label">To Date</label>
                            <input type="date" name="end_date" id="end_date" 
                                   class="form-control date-picker" 
                                   value="<?php echo htmlspecialchars($endDate); ?>" required>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-filter"></i> Filter
                            </button>
                        </div>
                    </div>
                </form>
            </div>
            
            <?php if ($accountId): ?>
                <!-- Statement Period -->
                <div class="statement-period">
                    <div class="row">
                        <div class="col-md-6">
                            <h5 class="mb-1">Statement Period</h5>
                            <p class="mb-0">
                                <?php echo date('F j, Y', strtotime($startDate)); ?> to 
                                <?php echo date('F j, Y', strtotime($endDate)); ?>
                            </p>
                        </div>
                        <div class="col-md-6 text-end">
                            <h5 class="mb-1">Member</h5>
                            <p class="mb-0">
                                <?php echo htmlspecialchars($member['first_name'] . ' ' . $member['last_name']); ?>
                                (<?php echo htmlspecialchars($member['member_number']); ?>)
                            </p>
                        </div>
                    </div>
                </div>
                
                <!-- Transaction Table -->
                <div class="table-responsive">
                    <table class="transaction-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Description</th>
                                <th>Reference</th>
                                <th>Type</th>
                                <th class="text-end">Amount</th>
                                <th class="text-end">Balance</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Opening Balance -->
                            <tr style="background-color: #f8f9fa;">
                                <td><?php echo date('M j, Y', strtotime($startDate)); ?></td>
                                <td colspan="3">Opening Balance</td>
                                <td class="text-end"></td>
                                <td class="text-end"><?php echo number_format($openingBalance, 2); ?></td>
                            </tr>
                            
                            <!-- Transactions -->
                            <?php if (empty($transactions)): ?>
                                <tr>
                                    <td colspan="6" class="text-center py-4 text-muted">
                                        No transactions found for this period
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($transactions as $transaction): ?>
                                    <tr>
                                        <td><?php echo date('M j, Y', strtotime($transaction['transaction_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($transaction['description']); ?></td>
                                        <td><?php echo htmlspecialchars($transaction['reference_number']); ?></td>
                                        <td><?php echo htmlspecialchars($transaction['transaction_type_name']); ?></td>
                                        <td class="text-end <?php echo $transaction['is_credit'] ? 'credit-amount' : 'debit-amount'; ?>">
                                            <?php echo ($transaction['is_credit'] ? '+' : '-') . number_format($transaction['amount'], 2); ?>
                                        </td>
                                        <td class="text-end"><?php echo number_format($transaction['balance_after'], 2); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            
                            <!-- Closing Balance -->
                            <tr style="background-color: #f8f9fa; font-weight: 600;">
                                <td><?php echo date('M j, Y', strtotime($endDate)); ?></td>
                                <td colspan="3">Closing Balance</td>
                                <td class="text-end"></td>
                                <td class="text-end"><?php echo number_format($closingBalance, 2); ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- Summary -->
                <div class="summary-card">
                    <div class="summary-item">
                        <span>Opening Balance:</span>
                        <span><?php echo number_format($openingBalance, 2); ?></span>
                    </div>
                    <div class="summary-item">
                        <span>Total Credits:</span>
                        <span class="credit-amount">
                            <?php 
                            $totalCredits = array_sum(array_map(function($t) { 
                                return $t['is_credit'] ? $t['amount'] : 0; 
                            }, $transactions));
                            echo number_format($totalCredits, 2); 
                            ?>
                        </span>
                    </div>
                    <div class="summary-item">
                        <span>Total Debits:</span>
                        <span class="debit-amount">
                            <?php 
                            $totalDebits = array_sum(array_map(function($t) { 
                                return !$t['is_credit'] ? $t['amount'] : 0; 
                            }, $transactions));
                            echo number_format($totalDebits, 2); 
                            ?>
                        </span>
                    </div>
                    <div class="summary-item">
                        <span>Net Movement:</span>
                        <span class="<?php echo ($totalCredits - $totalDebits) >= 0 ? 'credit-amount' : 'debit-amount'; ?>">
                            <?php echo number_format($totalCredits - $totalDebits, 2); ?>
                        </span>
                    </div>
                    <div class="summary-item">
                        <span>Closing Balance:</span>
                        <span><?php echo number_format($closingBalance, 2); ?></span>
                    </div>
                </div>
                
                <!-- Actions -->
                <div class="mt-4 no-print">
                    <div class="d-flex justify-content-between">
                        <div>
                            <button onclick="window.print()" class="print-btn me-2">
                                <i class="fas fa-print"></i> Print Statement
                            </button>
                            <a href="export_statement.php?account_id=<?php echo $accountId; ?>&start_date=<?php echo $startDate; ?>&end_date=<?php echo $endDate; ?>" 
                               class="btn btn-outline-primary">
                                <i class="fas fa-file-export"></i> Export as PDF
                            </a>
                        </div>
                        <div>
                            <a href="dashboard.php" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left"></i> Back to Dashboard
                            </a>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <div class="alert alert-info text-center py-4">
                    <i class="fas fa-info-circle fa-2x mb-3"></i>
                    <h4>Select an account to view statement</h4>
                    <p class="mb-0">Please choose an account and date range to generate your statement</p>
                </div>
            <?php endif; ?>
            
            <!-- Footer -->
            <div class="mt-5 pt-3 border-top text-muted small">
                <div class="row">
                    <div class="col-md-6">
                        <p>Generated on: <?php echo date('F j, Y \a\t H:i'); ?></p>
                    </div>
                    <div class="col-md-6 text-end">
                        <p>Page 1 of 1</p>
                    </div>
                </div>
                <p class="text-center mt-2">
                    <?php echo $companyName; ?> - All rights reserved &copy; <?php echo date('Y'); ?>
                </p>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Set default end date to today
        document.getElementById('end_date').max = new Date().toISOString().split('T')[0];
        
        // Set start date max to end date
        document.getElementById('start_date').addEventListener('change', function() {
            document.getElementById('end_date').min = this.value;
        });
        
        // Set end date min to start date
        document.getElementById('end_date').addEventListener('change', function() {
            document.getElementById('start_date').max = this.value;
        });
        
        // Initialize date constraints
        if (document.getElementById('start_date').value && document.getElementById('end_date').value) {
            document.getElementById('end_date').min = document.getElementById('start_date').value;
            document.getElementById('start_date').max = document.getElementById('end_date').value;
        }
    </script>
</body>
</html>