<?php
// Start output buffering
ob_start();

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Include required files
require_once './includes/config.php';
require_once './auth/middleware.php';
require_once './vendor/autoload.php';
require_once './tcpdf/tcpdf.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$title = 'Member statement';
$subTitle = 'Member statement';

// Check if user is logged in as a member
if (!isset($_SESSION['member_id'])) {
    header("Location: member-login.php");
    exit;
}

// Get the logged-in member's ID
$memberId = $_SESSION['member_id'];

// Fetch the active financial year
$stmt = $pdo->query("SELECT id FROM financial_years WHERE is_active = 1 LIMIT 1");
$financial_year = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$financial_year) {
    die("Error: No active financial year.");
}
$financial_year_id = $financial_year['id'];

// Fetch member details
$member = $pdo->prepare("SELECT id, first_name, last_name, personal_number FROM members WHERE id = ?");
$member->execute([$memberId]);
$memberDetails = $member->fetch(PDO::FETCH_ASSOC);

if (!$memberDetails) {
    die("Error: Member not found.");
}

// Initialize variables
$statementHtml = null;

/**
 * Gets the opening balance for an account as of a specific date
 */
function getOpeningBalance($pdo, $accounttypeId, $startDate) {
    // First try to get the last balance before the start date
    $stmt = $pdo->prepare("
        SELECT running_balance 
        FROM transactions 
        WHERE account_type_id = ? 
        AND transaction_date < ? 
        ORDER BY transaction_date DESC, created_at DESC 
        LIMIT 1
    ");
    $stmt->execute([$accounttypeId, $startDate]);
    $openingBalance = $stmt->fetchColumn();
    
    // If no transactions before start date, get the account's opening balance
    if ($openingBalance === false) {
        $stmt = $pdo->prepare("
            SELECT opening_balance 
            FROM member_accounts 
            WHERE id = ?
        ");
        $stmt->execute([$accounttypeId]);
        $openingBalance = $stmt->fetchColumn();
    }
    
    return $openingBalance !== false ? (float)$openingBalance : 0.00;
}

/**
 * Processes transactions to calculate running balances
 */
function processTransactions($transactions, $openingBalance) {
    $currentBalance = $openingBalance;
    foreach ($transactions as &$transaction) {
        $transaction['opening_balance'] = $currentBalance;
        if ($transaction['transaction_type'] === 'cr') {
            $currentBalance += $transaction['amount'];
        } else {
            $currentBalance -= $transaction['amount'];
        }
        $transaction['running_balance'] = $currentBalance;
    }
    return [
        'transactions' => $transactions,
        'closing_balance' => $currentBalance
    ];
}

// Handle form submission for viewing the statement
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['view_statement'])) {
    $startDate = $_POST['start_date'];
    $endDate = $_POST['end_date'];
    $accounttypeId = $_POST['account_type_id']; // Selected account ID or "all"

    // Validate input
    if (empty($startDate) || empty($endDate)) {
        die("Error: Please fill all fields.");
    }

    // Fetch account details for the member
    $accounts = $pdo->prepare("
        SELECT 
            ma.id AS account_type_id, 
            ma.account_type_id, 
            ma.sub_account_code,
            at.account_name,
            at.type_code
        FROM member_accounts ma
        JOIN account_types at ON ma.account_type_id = at.id
        WHERE ma.member_id = ?
    ");
    $accounts->execute([$memberId]);
    $accountList = $accounts->fetchAll(PDO::FETCH_ASSOC);

    if (empty($accountList)) {
        die("Error: No accounts found for this member.");
    }

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

    // Fetch transactions
    if ($accounttypeId === 'all') {
        // Process all accounts
        $transactionsByAccount = [];
        foreach ($accountList as $account) {
            $openingBalance = getOpeningBalance($pdo, $account['account_type_id'], $startDate);
            
            // Get transactions for the period
            $stmt = $pdo->prepare("
                SELECT 
                    t.transaction_number, 
                    t.transaction_type, 
                    t.amount, 
                    t.payment_method, 
                    t.description, 
                    t.reference_number, 
                    t.transaction_date,
                    t.created_by,
                    u.username as created_by_name,
                    at.account_name as account_type_name,
                    t.sub_account_code
                FROM transactions t
                JOIN users u ON t.created_by = u.id
                JOIN account_types at ON t.account_type_id = at.id
                WHERE t.member_id = ? 
                AND t.account_type_id = ?
                AND t.transaction_date BETWEEN ? AND ?
                ORDER BY t.transaction_date ASC, t.created_at ASC
            ");
            $stmt->execute([$memberId, $account['account_type_id'], $startDate, $endDate]);
            $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $processed = processTransactions($transactions, $openingBalance);
            
            $transactionsByAccount[$account['account_name']] = [
                'transactions' => $processed['transactions'],
                'account_details' => $account,
                'opening_balance' => $openingBalance,
                'closing_balance' => $processed['closing_balance']
            ];
        }

        // Generate HTML for the statement
        $statementHtml = generateStatementHtml($companySettings, $memberDetails, $startDate, $endDate, 'All Accounts', $transactionsByAccount);
    } else {
        // Process single account
        $accountDetails = null;
        foreach ($accountList as $account) {
            if ($account['account_type_id'] == $accounttypeId) {
                $accountDetails = $account;
                break;
            }
        }

        if (!$accountDetails) {
            die("Error: Selected account not found.");
        }

        $openingBalance = getOpeningBalance($pdo, $accounttypeId, $startDate);
        
        // Get transactions for the period
        $stmt = $pdo->prepare("
            SELECT 
                t.transaction_number, 
                t.transaction_type, 
                t.amount, 
                t.payment_method, 
                t.description, 
                t.reference_number, 
                t.transaction_date,
                t.created_by,
                u.username as created_by_name,
                at.account_name as account_type_name,
                t.sub_account_code
            FROM transactions t
            JOIN users u ON t.created_by = u.id
            JOIN account_types at ON t.account_type_id = at.id
            WHERE t.member_id = ? 
            AND t.account_type_id = ?
            AND t.transaction_date BETWEEN ? AND ?
            ORDER BY t.transaction_date ASC, t.created_at ASC
        ");
        $stmt->execute([$memberId, $accounttypeId, $startDate, $endDate]);
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $processed = processTransactions($transactions, $openingBalance);
        
        // Generate HTML for the statement
        $statementHtml = generateStatementHtml($companySettings, $memberDetails, $startDate, $endDate, 
            $accountDetails['account_name'] . " (Sub Account: {$accountDetails['sub_account_code']})", 
            [$accountDetails['account_name'] => [
                'transactions' => $processed['transactions'],
                'account_details' => $accountDetails,
                'opening_balance' => $openingBalance,
                'closing_balance' => $processed['closing_balance']
            ]]
        );
    }
}

/**
 * Generates HTML for the statement
 */
function generateStatementHtml($companySettings, $memberDetails, $startDate, $endDate, $accountInfo, $transactionsByAccount) {
    $html = "
        <div class='statement-container'>
            <div class='statement-header'>
                <img src='{$companySettings['company_logo']}' alt='Company Logo' class='company-logo'>
                <h2 class='statement-title'>Member Statement</h2>
                <p><strong>Company Name:</strong> {$companySettings['company_name']}</p>
                <p><strong>Address:</strong> {$companySettings['address']}, {$companySettings['city']}, {$companySettings['country']}</p>
                <p><strong>Phone:</strong> {$companySettings['phone_number']}</p>
                <p><strong>Email:</strong> {$companySettings['email']}</p>
                <p><strong>Website:</strong> {$companySettings['website']}</p>
            </div>
            <hr>
            <div class='statement-details'>
                <p><strong>Member:</strong> {$memberDetails['first_name']} {$memberDetails['last_name']} (Personal Number: {$memberDetails['personal_number']})</p>
                <p><strong>Period:</strong> $startDate to $endDate</p>
                <p><strong>Account:</strong> $accountInfo</p>
            </div>";

    foreach ($transactionsByAccount as $accountName => $data) {
        $account = $data['account_details'];
        $transactions = $data['transactions'];
        
        $html .= "
            <div class='account-section'>
                <h4>Account: {$account['account_name']} (Sub Account: {$account['sub_account_code']})</h4>
                <p><strong>Opening Balance:</strong> " . number_format($data['opening_balance'], 2) . "</p>";
        
        if (!empty($transactions)) {
            $html .= "
                <div class='table-responsive'>
                    <table class='table table-bordered'>
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Transaction #</th>
                                <th>Type</th>
                                <th>Amount</th>
                                <th>Running Balance</th>
                                <th>Payment Method</th>
                                <th>Description</th>
                                <th>Reference</th>
                                <th>Processed By</th>
                            </tr>
                        </thead>
                        <tbody>";
            
            foreach ($transactions as $transaction) {
                $html .= "
                    <tr>
                        <td>{$transaction['transaction_date']}</td>
                        <td>{$transaction['transaction_number']}</td>
                        <td>" . strtoupper($transaction['transaction_type']) . "</td>
                        <td>" . number_format($transaction['amount'], 2) . "</td>
                        <td>" . number_format($transaction['running_balance'], 2) . "</td>
                        <td>{$transaction['payment_method']}</td>
                        <td>{$transaction['description']}</td>
                        <td>{$transaction['reference_number']}</td>
                        <td>{$transaction['created_by_name']}</td>
                    </tr>";
            }
            
            $html .= "
                        </tbody>
                    </table>
                </div>";
        } else {
            $html .= "<p>No transactions during this period.</p>";
        }
        
        $html .= "
                <p><strong>Closing Balance:</strong> " . number_format($data['closing_balance'], 2) . "</p>
            </div>";
    }
    
    $html .= "</div>";
    
    return $html;
}

// Handle download request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['download_statement'])) {
    $startDate = $_POST['start_date'];
    $endDate = $_POST['end_date'];
    $accounttypeId = $_POST['account_type_id'];
    $format = $_POST['format'];

    // Validate input
    if (empty($startDate) || empty($endDate) || empty($accounttypeId) || empty($format)) {
        die("Error: Please fill all fields.");
    }

    // Fetch account details for the member
    $accounts = $pdo->prepare("
        SELECT 
            ma.id AS account_type_id, 
            ma.account_type_id, 
            ma.sub_account_code,
            at.account_name,
            at.type_code
        FROM member_accounts ma
        JOIN account_types at ON ma.account_type_id = at.id
        WHERE ma.member_id = ?
    ");
    $accounts->execute([$memberId]);
    $accountList = $accounts->fetchAll(PDO::FETCH_ASSOC);

    if (empty($accountList)) {
        die("Error: No accounts found for this member.");
    }

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

    // Process transactions based on account selection
    $transactionsByAccount = [];
    
    if ($accounttypeId === 'all') {
        foreach ($accountList as $account) {
            $openingBalance = getOpeningBalance($pdo, $account['account_type_id'], $startDate);
            
            $stmt = $pdo->prepare("
                SELECT 
                    t.transaction_number, 
                    t.transaction_type, 
                    t.amount, 
                    t.payment_method, 
                    t.description, 
                    t.reference_number, 
                    t.transaction_date,
                    t.created_by,
                    u.username as created_by_name,
                    at.account_name as account_type_name,
                    t.sub_account_code
                FROM transactions t
                JOIN users u ON t.created_by = u.id
                JOIN account_types at ON t.account_type_id = at.id
                WHERE t.member_id = ? 
                AND t.account_type_id = ?
                AND t.transaction_date BETWEEN ? AND ?
                ORDER BY t.transaction_date ASC, t.created_at ASC
            ");
            $stmt->execute([$memberId, $account['account_type_id'], $startDate, $endDate]);
            $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $processed = processTransactions($transactions, $openingBalance);
            
            $transactionsByAccount[$account['account_name']] = [
                'transactions' => $processed['transactions'],
                'account_details' => $account,
                'opening_balance' => $openingBalance,
                'closing_balance' => $processed['closing_balance']
            ];
        }
    } else {
        $accountDetails = null;
        foreach ($accountList as $account) {
            if ($account['account_type_id'] == $accounttypeId) {
                $accountDetails = $account;
                break;
            }
        }

        if (!$accountDetails) {
            die("Error: Selected account not found.");
        }

        $openingBalance = getOpeningBalance($pdo, $accounttypeId, $startDate);
        
        $stmt = $pdo->prepare("
            SELECT 
                t.transaction_number, 
                t.transaction_type, 
                t.amount, 
                t.payment_method, 
                t.description, 
                t.reference_number, 
                t.transaction_date,
                t.created_by,
                u.username as created_by_name,
                at.account_name as account_type_name,
                t.sub_account_code
            FROM transactions t
            JOIN users u ON t.created_by = u.id
            JOIN account_types at ON t.account_type_id = at.id
            WHERE t.member_id = ? 
            AND t.account_type_id = ?
            AND t.transaction_date BETWEEN ? AND ?
            ORDER BY t.transaction_date ASC, t.created_at ASC
        ");
        $stmt->execute([$memberId, $accounttypeId, $startDate, $endDate]);
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $processed = processTransactions($transactions, $openingBalance);
        
        $transactionsByAccount[$accountDetails['account_name']] = [
            'transactions' => $processed['transactions'],
            'account_details' => $accountDetails,
            'opening_balance' => $openingBalance,
            'closing_balance' => $processed['closing_balance']
        ];
    }

    // Generate the statement based on the selected format
    if ($format === 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="member_statement_' . $memberDetails['personal_number'] . '_' . date('YmdHis') . '.csv"');

        $output = fopen('php://output', 'w');

        // CSV header
        fputcsv($output, [
            'Account Name', 
            'Sub Account Code', 
            'Transaction Date', 
            'Transaction Number',
            'Transaction Type', 
            'Amount', 
            'Running Balance',
            'Payment Method', 
            'Description', 
            'Reference Number',
            'Processed By'
        ]);

        // CSV rows
        foreach ($transactionsByAccount as $accountName => $data) {
            $account = $data['account_details'];
            
            // Add opening balance row
            fputcsv($output, [
                $accountName,
                $account['sub_account_code'],
                $startDate,
                'OPENING BALANCE',
                '',
                '',
                $data['opening_balance'],
                '',
                '',
                '',
                ''
            ]);
            
            // Add transaction rows
            foreach ($data['transactions'] as $transaction) {
                fputcsv($output, [
                    $accountName,
                    $account['sub_account_code'],
                    $transaction['transaction_date'],
                    $transaction['transaction_number'],
                    strtoupper($transaction['transaction_type']),
                    $transaction['amount'],
                    $transaction['running_balance'],
                    $transaction['payment_method'],
                    $transaction['description'],
                    $transaction['reference_number'],
                    $transaction['created_by_name']
                ]);
            }
            
            // Add closing balance row
            fputcsv($output, [
                $accountName,
                $account['sub_account_code'],
                $endDate,
                'CLOSING BALANCE',
                '',
                '',
                $data['closing_balance'],
                '',
                '',
                '',
                ''
            ]);
            
            // Add empty row between accounts
            fputcsv($output, []);
        }

        fclose($output);
        exit;
    } elseif ($format === 'pdf') {
        // Generate PDF using TCPDF
        
        // Create new PDF document
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        
        // Set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor($companySettings['company_name']);
        $pdf->SetTitle('Member Statement - ' . $memberDetails['first_name'] . ' ' . $memberDetails['last_name']);
        $pdf->SetSubject('Member Account Statement');
        
        // Set default header data
        $pdf->SetHeaderData($companySettings['company_logo'] ?? '', 20, 
            $companySettings['company_name'], "Member Statement\n" . 
            $memberDetails['first_name'] . ' ' . $memberDetails['last_name'] . 
            ' (' . $memberDetails['personal_number'] . ')');
        
        // Set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        
        // Set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        
        // Set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        
        // Add a page
        $pdf->AddPage();
        
        // Set font
        $pdf->SetFont('helvetica', '', 10);
        
        // Generate PDF content
        $html = '<h2>Statement Period: ' . $startDate . ' to ' . $endDate . '</h2>';
        
        foreach ($transactionsByAccount as $accountName => $data) {
            $account = $data['account_details'];
            
            $html .= '<h3>Account: ' . $accountName . ' (Sub Account: ' . $account['sub_account_code'] . ')</h3>';
            $html .= '<p><strong>Opening Balance:</strong> ' . number_format($data['opening_balance'], 2) . '</p>';
            
            if (!empty($data['transactions'])) {
                $html .= '<table border="1" cellpadding="4">
                    <tr>
                        <th width="15%">Date</th>
                        <th width="15%">Transaction #</th>
                        <th width="8%">Type</th>
                        <th width="12%">Amount</th>
                        <th width="15%">Running Balance</th>
                        <th width="10%">Payment Method</th>
                        <th width="15%">Description</th>
                        <th width="10%">Reference</th>
                    </tr>';
                
                foreach ($data['transactions'] as $transaction) {
                    $html .= '<tr>
                        <td>' . $transaction['transaction_date'] . '</td>
                        <td>' . $transaction['transaction_number'] . '</td>
                        <td>' . strtoupper($transaction['transaction_type']) . '</td>
                        <td>' . number_format($transaction['amount'], 2) . '</td>
                        <td>' . number_format($transaction['running_balance'], 2) . '</td>
                        <td>' . $transaction['payment_method'] . '</td>
                        <td>' . $transaction['description'] . '</td>
                        <td>' . $transaction['reference_number'] . '</td>
                    </tr>';
                }
                
                $html .= '</table>';
            } else {
                $html .= '<p>No transactions during this period.</p>';
            }
            
            $html .= '<p><strong>Closing Balance:</strong> ' . number_format($data['closing_balance'], 2) . '</p><br>';
        }
        
        // Output HTML content
        $pdf->writeHTML($html, true, false, true, false, '');
        
        // Close and output PDF document
        $pdf->Output('member_statement_' . $memberDetails['personal_number'] . '_' . date('YmdHis') . '.pdf', 'D');
        exit;
    } else {
        die("Invalid format selected.");
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Account Statement</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Animate.css -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    <style>
        :root {
            --primary-color: #0052A5;
            --secondary-color: #6c757d;
            --accent-color: #00a8e8;
            --light-bg: #f8f9fa;
            --card-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        }
        
        body {
            background-color: var(--light-bg);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            transition: transform 0.3s ease;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .form-control, .form-select {
            border-radius: 8px;
            padding: 10px 15px;
            border: 1px solid #e0e0e0;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--accent-color);
            box-shadow: 0 0 0 0.25rem rgba(0, 168, 232, 0.25);
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            background-color: #003d7a;
            transform: translateY(-2px);
        }
        
        .btn-success {
            background-color: #28a745;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-success:hover {
            background-color: #218838;
            transform: translateY(-2px);
        }
        
        .statement-container {
            max-width: 100%;
            margin: 0 auto;
            padding: 30px;
            border: 1px solid #EEE;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
        }
        
        .statement-header {
            text-align: center;
            margin-bottom: 25px;
            padding-bottom: 20px;
            border-bottom: 1px dashed #DDD;
        }
        
        .statement-title {
            font-size: 26px;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 10px;
        }
        
        .company-logo {
            max-height: 80px;
            margin-bottom: 15px;
        }
        
        .loading-spinner {
            display: none;
            text-align: center;
            margin: 20px 0;
        }
        
        .date-info {
            font-size: 0.9rem;
            color: var(--secondary-color);
            margin-top: 5px;
        }
        
        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 25px;
            flex-wrap: wrap;
        }
        
        .action-buttons .btn {
            flex: 1;
            min-width: 200px;
        }
        
        .preview-section {
            margin-top: 30px;
            animation: fadeIn 0.5s ease-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @media print {
            body * {
                visibility: hidden;
            }
            .statement-container, .statement-container * {
                visibility: visible;
            }
            .statement-container {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                box-shadow: none;
                border: none;
            }
            .no-print {
                display: none !important;
            }
        }
        
        /* Modern select2 styling */
        .select2-container--default .select2-selection--single {
            height: auto;
            padding: 8px 15px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 100%;
        }
    </style>
</head>
<body class="bg-light">
    <?php include './partials/layouts/layoutTop.php' ?>
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="card p-4 animate__animated animate__fadeIn">
                    <h2 class="text-center mb-4">
                        <i class="fas fa-file-invoice me-2"></i>My Account Statement
                    </h2>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        You are viewing the statement for: <strong><?= htmlspecialchars($memberDetails['first_name'] . ' ' . $memberDetails['last_name']) ?></strong>
                        (Personal Number: <?= htmlspecialchars($memberDetails['personal_number']) ?>)
                    </div>
                    
                    <!-- Form -->
                    <form action="" method="POST" class="mt-3 needs-validation" novalidate>
                        <div class="row g-3">
                            <!-- Date Range -->
                            <div class="col-md-3">
                                <label for="start_date" class="form-label fw-semibold">
                                    <i class="fas fa-calendar-day me-2"></i>Start Date
                                </label>
                                <input type="date" name="start_date" id="start_date" class="form-control" required>
                                <div class="invalid-feedback">
                                    Please select a start date.
                                </div>
                                <div class="date-info" id="start_date_info"></div>
                            </div>

                            <div class="col-md-3">
                                <label for="end_date" class="form-label fw-semibold">
                                    <i class="fas fa-calendar-day me-2"></i>End Date
                                </label>
                                <input type="date" name="end_date" id="end_date" class="form-control" required>
                                <div class="invalid-feedback">
                                    Please select an end date.
                                </div>
                                <div class="date-info" id="end_date_info"></div>
                            </div>

                            <!-- Account Selection -->
                            <div class="col-md-6">
                                <label for="account_type_id" class="form-label fw-semibold">
                                    <i class="fas fa-wallet me-2"></i>Account
                                </label>
                                <select name="account_type_id" id="account_type_id" class="form-select select2" required>
                                    <option value="all">All Accounts</option>
                                    <?php
                                    // Fetch accounts for the logged-in member
                                    $accounts = $pdo->prepare("
                                        SELECT ma.id AS account_type_id, at.account_name 
                                        FROM member_accounts ma
                                        JOIN account_types at ON ma.account_type_id = at.id
                                        WHERE ma.member_id = ?
                                    ");
                                    $accounts->execute([$memberId]);
                                    $accountList = $accounts->fetchAll(PDO::FETCH_ASSOC);

                                    foreach ($accountList as $account) {
                                        echo "<option value='" . htmlspecialchars($account['account_type_id']) . "'>" . 
                                             htmlspecialchars($account['account_name']) . "</option>";
                                    }
                                    ?>
                                </select>
                                <div class="invalid-feedback">
                                    Please select an account.
                                </div>
                            </div>
                        </div>

                        <!-- Quick Date Selectors -->
                        <div class="row mt-3">
                            <div class="col-12">
                                <div class="btn-group w-100" role="group">
                                    <button type="button" class="btn btn-outline-secondary quick-date" data-days="7">1 Week</button>
                                    <button type="button" class="btn btn-outline-secondary quick-date" data-days="30">1 Month</button>
                                    <button type="button" class="btn btn-outline-secondary quick-date" data-days="90">3 Months</button>
                                    <button type="button" class="btn btn-outline-secondary quick-date" data-days="365">1 Year</button>
                                </div>
                            </div>
                        </div>

                        <!-- Submit Button -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <button type="submit" name="view_statement" class="btn btn-primary w-100 py-3">
                                    <i class="fas fa-eye me-2"></i>Generate Statement
                                </button>
                            </div>
                        </div>
                    </form>

                    <!-- Loading Spinner -->
                    <div class="loading-spinner" id="loadingSpinner">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">Generating your statement...</p>
                    </div>

                    <!-- Display Statement -->
                    <?php if ($statementHtml): ?>
                        <div class="preview-section animate__animated animate__fadeIn">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h3 class="mb-0">
                                    <i class="fas fa-file-alt me-2"></i>Statement Preview
                                </h3>
                                <div class="badge bg-primary">
                                    <?= htmlspecialchars($_POST['start_date']) ?> to <?= htmlspecialchars($_POST['end_date']) ?>
                                </div>
                            </div>
                            
                            <?= $statementHtml ?>
                            
                            <div class="alert alert-info mt-3">
                                <i class="fas fa-info-circle me-2"></i>
                                Review your statement above before downloading or printing.
                            </div>
                            
                            <form action="" method="POST" class="mt-4">
                                <input type="hidden" name="member_id" value="<?= htmlspecialchars($memberId) ?>">
                                <input type="hidden" name="start_date" value="<?= htmlspecialchars($_POST['start_date']) ?>">
                                <input type="hidden" name="end_date" value="<?= htmlspecialchars($_POST['end_date']) ?>">
                                <input type="hidden" name="account_type_id" value="<?= htmlspecialchars($_POST['account_type_id']) ?>">
                                
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label for="format" class="form-label fw-semibold">
                                            <i class="fas fa-file-download me-2"></i>Download Format
                                        </label>
                                        <select name="format" id="format" class="form-select" required>
                                            <option value="csv">CSV (Excel compatible)</option>
                                            <option value="pdf">PDF (Printable format)</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 d-flex align-items-end">
                                        <button type="submit" name="download_statement" class="btn btn-success w-100 py-3">
                                            <i class="fas fa-download me-2"></i>Download Statement
                                        </button>
                                    </div>
                                </div>
                            </form>
                            
                            <div class="action-buttons no-print">
                                <button onclick="window.print()" class="btn btn-secondary">
                                    <i class="fas fa-print me-2"></i>Print Statement
                                </button>
                                <button id="emailStatement" class="btn btn-info">
                                    <i class="fas fa-envelope me-2"></i>Email Statement
                                </button>
                                <button id="saveAsPdf" class="btn btn-warning">
                                    <i class="fas fa-file-pdf me-2"></i>Save as PDF
                                </button>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function () {
            // Initialize Select2 dropdowns
            $('.select2').select2({
                placeholder: 'Select an option',
                allowClear: true,
                width: '100%'
            });

            // Set default dates (first day of current month to today)
            const today = new Date();
            const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
            
            $('#start_date').val(formatDate(firstDay));
            $('#end_date').val(formatDate(today));
            
            // Update date info display
            updateDateInfo('start_date');
            updateDateInfo('end_date');
            
            // Date info display on change
            $('#start_date, #end_date').change(function() {
                updateDateInfo(this.id);
                validateDateRange();
            });

            // Quick date selectors
            $('.quick-date').click(function() {
                const days = parseInt($(this).data('days'));
                const endDate = new Date();
                const startDate = new Date();
                startDate.setDate(endDate.getDate() - days);
                
                $('#start_date').val(formatDate(startDate));
                $('#end_date').val(formatDate(endDate));
                
                updateDateInfo('start_date');
                updateDateInfo('end_date');
                validateDateRange();
            });

            // Form validation
            $('form').submit(function(e) {
                if (!this.checkValidity()) {
                    e.preventDefault();
                    e.stopPropagation();
                } else {
                    $('#loadingSpinner').show();
                }
                
                $(this).addClass('was-validated');
            });
            
            // Email statement button
            $('#emailStatement').click(function() {
                alert('Email functionality will be implemented here');
                // You would typically open a modal with an email form here
            });
            
            // Save as PDF button
            $('#saveAsPdf').click(function() {
                alert('PDF generation will be implemented here');
                // You would typically call a PDF generation function here
            });

            // Helper function to format date as YYYY-MM-DD
            function formatDate(date) {
                const d = new Date(date);
                let month = '' + (d.getMonth() + 1);
                let day = '' + d.getDate();
                const year = d.getFullYear();

                if (month.length < 2) month = '0' + month;
                if (day.length < 2) day = '0' + day;

                return [year, month, day].join('-');
            }
            
            // Update date info display
            function updateDateInfo(id) {
                const dateStr = $('#' + id).val();
                if (dateStr) {
                    const date = new Date(dateStr);
                    const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
                    $('#' + id + '_info').text(date.toLocaleDateString('en-US', options));
                } else {
                    $('#' + id + '_info').text('');
                }
            }
            
            // Validate date range
            function validateDateRange() {
                const startDate = new Date($('#start_date').val());
                const endDate = new Date($('#end_date').val());
                
                if (startDate && endDate && startDate > endDate) {
                    $('#end_date').addClass('is-invalid');
                    $('#end_date').next('.invalid-feedback').text('End date must be after start date');
                } else {
                    $('#end_date').removeClass('is-invalid');
                }
            }
        });
    </script>
</body>
</html>
<?php include './partials/layouts/layoutBottom.php' ?>