<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$success_message = "";
$error_message = "";
$selected_bank_id = isset($_GET['bank_id']) ? $_GET['bank_id'] : (isset($_POST['bank_id']) ? $_POST['bank_id'] : '');

// Get all bank accounts
$banks_sql = "SELECT * FROM bank_accounts ORDER BY bank_name";
$banks_result = mysqli_query($conn, $banks_sql);

// Get bank details if selected
$bank_name = "";
$current_balance = 0;
$account_title = "";
$account_number = "";
if($selected_bank_id) {
    $bank_sql = "SELECT * FROM bank_accounts WHERE id = '$selected_bank_id'";
    $bank_result = mysqli_query($conn, $bank_sql);
    if($bank_data = mysqli_fetch_assoc($bank_result)) {
        $bank_name = $bank_data['bank_name'];
        $current_balance = $bank_data['balance'];
        $account_title = $bank_data['account_title'];
        $account_number = $bank_data['account_number'];
    }
}

// Add Bank Entry
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_entry'])) {
    $bank_id = mysqli_real_escape_string($conn, $_POST['bank_id']);
    $entry_type = mysqli_real_escape_string($conn, $_POST['entry_type']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $reference_no = mysqli_real_escape_string($conn, $_POST['reference_no']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($bank_id) || empty($entry_type) || $amount <= 0) {
        $error_message = "Please select bank account, entry type and enter valid amount!";
    } else {
        mysqli_begin_transaction($conn);
        
        try {
            // Get current balance
            $balance_sql = "SELECT balance FROM bank_accounts WHERE id = '$bank_id'";
            $balance_result = mysqli_query($conn, $balance_sql);
            $bank = mysqli_fetch_assoc($balance_result);
            $new_balance = $bank['balance'];
            
            // Calculate new balance based on entry type
            if($entry_type == 'Deposit' || $entry_type == 'Online Receive') {
                // Add to bank balance
                $new_balance = $bank['balance'] + $amount;
                $balance_change = "+" . $amount;
            } elseif($entry_type == 'Withdrawal' || $entry_type == 'Bank Expense') {
                // Deduct from bank balance
                if($amount > $bank['balance']) {
                    throw new Exception("Insufficient balance! Available: Rs " . number_format($bank['balance'], 2));
                }
                $new_balance = $bank['balance'] - $amount;
                $balance_change = "-" . $amount;
            }
            
            // Insert bank book entry
            $insert_sql = "INSERT INTO bank_book (bank_id, entry_type, amount, description, reference_no, date_time) 
                           VALUES ('$bank_id', '$entry_type', '$amount', '$description', '$reference_no', '$date_time')";
            mysqli_query($conn, $insert_sql);
            
            // Update bank account balance
            $update_sql = "UPDATE bank_accounts SET balance = '$new_balance' WHERE id = '$bank_id'";
            mysqli_query($conn, $update_sql);
            
            mysqli_commit($conn);
            $success_message = "Bank entry added successfully!";
            
            // Refresh balance
            $bank_sql = "SELECT * FROM bank_accounts WHERE id = '$bank_id'";
            $bank_result = mysqli_query($conn, $bank_sql);
            if($bank_data = mysqli_fetch_assoc($bank_result)) {
                $current_balance = $bank_data['balance'];
            }
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Get bank book entries for selected bank
$bank_entries = [];
$total_deposits = 0;
$total_withdrawals = 0;
$total_online_receive = 0;
$total_bank_expense = 0;

if($selected_bank_id) {
    $entries_sql = "SELECT * FROM bank_book WHERE bank_id = '$selected_bank_id' ORDER BY id DESC";
    $entries_result = mysqli_query($conn, $entries_sql);
    
    while($entry = mysqli_fetch_assoc($entries_result)) {
        $bank_entries[] = $entry;
        
        if($entry['entry_type'] == 'Deposit') {
            $total_deposits += $entry['amount'];
        } elseif($entry['entry_type'] == 'Withdrawal') {
            $total_withdrawals += $entry['amount'];
        } elseif($entry['entry_type'] == 'Online Receive') {
            $total_online_receive += $entry['amount'];
        } elseif($entry['entry_type'] == 'Bank Expense') {
            $total_bank_expense += $entry['amount'];
        }
    }
}

$total_inflow = $total_deposits + $total_online_receive;
$total_outflow = $total_withdrawals + $total_bank_expense;
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bank Book</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');
        
        * { font-family: 'Poppins', sans-serif; }
        h1, h2, h3, h4, h5, h6 { font-family: 'Times New Roman', serif; }
        body { background: #f5f5f5; }
        
        .page-header {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            border-radius: 15px;
            padding: 25px 30px;
            margin-bottom: 30px;
            color: #fff;
        }
        .page-header h2 { margin: 0 0 8px 0; font-size: 28px; color: #fff; }
        .page-header p { margin: 0; opacity: 0.95; font-weight: 500; }
        
        .form-card, .table-card, .summary-card {
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 30px;
        }
        .card-header-custom {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            padding: 15px 20px;
            color: #fff;
        }
        .card-header-custom h4 { margin: 0; font-size: 18px; }
        .card-header-custom i { margin-right: 10px; }
        .card-body-custom { padding: 25px; }
        
        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }
        .form-label i { color: #A04657; margin-right: 8px; }
        .form-control, .form-select {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 12px 15px;
            font-weight: 500;
        }
        .form-control:focus, .form-select:focus {
            border-color: #A04657;
            box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
        }
        
        .btn-submit {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            color: #fff;
            border: none;
            padding: 12px 30px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 16px;
            width: 100%;
        }
        .btn-submit:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(160,70,87,0.3); color: #fff; }
        .btn-back {
            background: #6c757d;
            color: #fff;
            padding: 8px 20px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
        }
        .btn-back:hover { background: #5a6268; color: #fff; }
        
        .alert-custom {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 500;
        }
        .alert-success { background: #d4edda; color: #155724; border-left: 4px solid #28a745; }
        .alert-danger { background: #f8d7da; color: #721c24; border-left: 4px solid #dc3545; }
        
        .summary-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .stat-item {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 15px;
            text-align: center;
            border-left: 3px solid #A04657;
        }
        .stat-label-sm { font-size: 12px; color: #666; font-weight: 500; margin-bottom: 5px; }
        .stat-value-sm { font-size: 20px; font-weight: 700; }
        
        .balance-card {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            color: #fff;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
        }
        .balance-card .label { font-size: 14px; opacity: 0.9; margin-bottom: 10px; }
        .balance-card .amount { font-size: 32px; font-weight: 700; }
        
        .table th {
            background: #f8f9fa;
            font-weight: 700;
            color: #444;
        }
        .table td { vertical-align: middle; font-weight: 500; }
        
        .badge-deposit { background: #28a745; color: #fff; padding: 5px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .badge-withdrawal { background: #dc3545; color: #fff; padding: 5px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .badge-online { background: #17a2b8; color: #fff; padding: 5px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .badge-expense { background: #fd7e14; color: #fff; padding: 5px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        
        .amount-positive { color: #28a745; font-weight: 700; }
        .amount-negative { color: #dc3545; font-weight: 700; }
        
        .bank-info-card {
            background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid #28a745;
        }
        .info-row { display: flex; justify-content: space-between; padding: 6px 0; }
        .info-row span { font-size: 13px; color: #2e7d32; font-weight: 500; }
        .info-row strong { font-size: 14px; color: #1b5e20; font-weight: 600; }
        
        .required { color: #dc3545; }
        
        @media (max-width: 768px) {
            .page-header { padding: 20px; }
            .page-header h2 { font-size: 22px; }
            .balance-card .amount { font-size: 24px; }
            .summary-stats { grid-template-columns: repeat(2, 1fr); }
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="page-header">
        <div>
            <h2><i class="fas fa-book"></i> Bank Book</h2>
            <p>Manage bank deposits, withdrawals, online receives and bank expenses</p>
        </div>
        </br>
        <div>
            <a href="bank_accounts.php" class="btn-back">
                <i class="fas fa-arrow-left"></i> Back to Accounts
            </a>
        </div>
    </div>
    
    <?php if($success_message): ?>
        <div class="alert-custom alert-success"><i class="fas fa-check-circle fa-lg"></i> <?php echo $success_message; ?></div>
    <?php endif; ?>
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger"><i class="fas fa-exclamation-triangle fa-lg"></i> <?php echo $error_message; ?></div>
    <?php endif; ?>
    
    <div class="row">
        <div class="col-lg-5">
            <div class="form-card">
                <div class="card-header-custom">
                    <h4><i class="fas fa-plus-circle"></i> Add Bank Entry</h4>
                </div>
                <div class="card-body-custom">
                    <form method="POST" action="">
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-university"></i> Select Bank Account <span class="required">*</span></label>
                            <select name="bank_id" id="bank_id" class="form-select" required>
                                <option value="">-- Select Bank Account --</option>
                                <?php 
                                mysqli_data_seek($banks_result, 0);
                                while($bank = mysqli_fetch_assoc($banks_result)): 
                                    $selected = ($selected_bank_id == $bank['id']) ? 'selected' : '';
                                ?>
                                    <option value="<?php echo $bank['id']; ?>" <?php echo $selected; ?>>
                                        <?php echo htmlspecialchars($bank['bank_name']); ?> - <?php echo htmlspecialchars($bank['account_title']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        
                        <?php if($selected_bank_id): ?>
                            <div class="bank-info-card">
                                <div class="info-row"><span><i class="fas fa-university"></i> Bank:</span><strong><?php echo htmlspecialchars($bank_name); ?></strong></div>
                                <div class="info-row"><span><i class="fas fa-user"></i> Account Title:</span><strong><?php echo htmlspecialchars($account_title); ?></strong></div>
                                <div class="info-row"><span><i class="fas fa-credit-card"></i> Account Number:</span><strong><?php echo htmlspecialchars($account_number); ?></strong></div>
                            </div>
                            <div class="balance-card">
                                <div class="label">Current Bank Balance</div>
                                <div class="amount">Rs <?php echo number_format($current_balance, 2); ?></div>
                            </div>
                        <?php endif; ?>
                        
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-tag"></i> Entry Type <span class="required">*</span></label>
                            <select name="entry_type" id="entry_type" class="form-select" required>
                                <option value="">-- Select Entry Type --</option>
                                <option value="Deposit">💰 Deposit (Cash IN to Bank)</option>
                                <option value="Withdrawal">🏧 Withdrawal (Cash OUT from Bank)</option>
                                <option value="Online Receive">📱 Online Receive (Digital IN)</option>
                                <option value="Bank Expense">📄 Bank Expense (Charges/Fees)</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-rupee-sign"></i> Amount <span class="required">*</span></label>
                            <input type="number" step="0.01" name="amount" class="form-control" placeholder="Enter amount" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-hashtag"></i> Reference Number</label>
                            <input type="text" name="reference_no" class="form-control" placeholder="e.g., Cheque #, Transaction ID, Slip #">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-file-alt"></i> Description</label>
                            <textarea name="description" class="form-control" rows="3" placeholder="Enter description (e.g., Cash deposit, ATM withdrawal, Bill payment)"></textarea>
                        </div>
                        
                        <button type="submit" name="add_entry" class="btn-submit">
                            <i class="fas fa-save"></i> Add Entry
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-7">
            <?php if($selected_bank_id): ?>
                <div class="summary-card">
                    <div class="card-header-custom">
                        <h4><i class="fas fa-chart-pie"></i> Bank Summary: <?php echo htmlspecialchars($bank_name); ?></h4>
                    </div>
                    <div class="card-body-custom">
                        <div class="summary-stats">
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-arrow-down"></i> Total Deposits</div>
                                <div class="stat-value-sm amount-positive">Rs <?php echo number_format($total_deposits, 2); ?></div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-mobile-alt"></i> Online Receives</div>
                                <div class="stat-value-sm amount-positive">Rs <?php echo number_format($total_online_receive, 2); ?></div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-arrow-up"></i> Total Withdrawals</div>
                                <div class="stat-value-sm amount-negative">Rs <?php echo number_format($total_withdrawals, 2); ?></div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-receipt"></i> Bank Expenses</div>
                                <div class="stat-value-sm amount-negative">Rs <?php echo number_format($total_bank_expense, 2); ?></div>
                            </div>
                        </div>
                        <div class="summary-stats">
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-chart-line"></i> Total Inflow</div>
                                <div class="stat-value-sm amount-positive">Rs <?php echo number_format($total_inflow, 2); ?></div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-chart-line"></i> Total Outflow</div>
                                <div class="stat-value-sm amount-negative">Rs <?php echo number_format($total_outflow, 2); ?></div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-calculator"></i> Net Change</div>
                                <div class="stat-value-sm <?php echo ($total_inflow - $total_outflow) >= 0 ? 'amount-positive' : 'amount-negative'; ?>">
                                    Rs <?php echo number_format(abs($total_inflow - $total_outflow), 2); ?>
                                    <?php echo ($total_inflow - $total_outflow) >= 0 ? '(Increase)' : '(Decrease)'; ?>
                                </div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-university"></i> Current Balance</div>
                                <div class="stat-value-sm" style="color: #A04657;">Rs <?php echo number_format($current_balance, 2); ?></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="table-card">
                    <div class="card-header-custom">
                        <h4><i class="fas fa-history"></i> Transaction History</h4>
                    </div>
                    <div class="card-body-custom">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr><th>ID</th><th>Entry Type</th><th>Amount</th><th>Reference No</th><th>Description</th><th>Date & Time</th></tr>
                                </thead>
                                <tbody>
                                    <?php if(count($bank_entries) > 0): ?>
                                        <?php foreach($bank_entries as $entry): ?>
                                            <tr>
                                                <td>#<?php echo $entry['id']; ?></div>
                                                <td>
                                                    <?php if($entry['entry_type'] == 'Deposit'): ?>
                                                        <span class="badge-deposit"><i class="fas fa-arrow-down"></i> Deposit</span>
                                                    <?php elseif($entry['entry_type'] == 'Withdrawal'): ?>
                                                        <span class="badge-withdrawal"><i class="fas fa-arrow-up"></i> Withdrawal</span>
                                                    <?php elseif($entry['entry_type'] == 'Online Receive'): ?>
                                                        <span class="badge-online"><i class="fas fa-mobile-alt"></i> Online Receive</span>
                                                    <?php else: ?>
                                                        <span class="badge-expense"><i class="fas fa-receipt"></i> Bank Expense</span>
                                                    <?php endif; ?>
                                                </div>
                                                <td class="<?php echo ($entry['entry_type'] == 'Deposit' || $entry['entry_type'] == 'Online Receive') ? 'amount-positive' : 'amount-negative'; ?>">
                                                    <?php echo ($entry['entry_type'] == 'Deposit' || $entry['entry_type'] == 'Online Receive') ? '+' : '-'; ?> Rs <?php echo number_format($entry['amount'], 2); ?>
                                                </div>
                                                <td><?php echo htmlspecialchars($entry['reference_no'] ?: '—'); ?></div>
                                                <td><?php echo htmlspecialchars($entry['description'] ?: '—'); ?></div>
                                                <td>
                                                    <i class="fas fa-calendar-alt"></i> <?php echo date('d-m-Y', strtotime($entry['date_time'])); ?>
                                                    <br><small><?php echo date('h:i A', strtotime($entry['date_time'])); ?></small>
                                                </div>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr><td colspan="6" class="text-center py-5"><i class="fas fa-book" style="font-size: 48px; color: #ccc;"></i><p class="mt-3">No bank entries found</p><small>Add entries to see transaction history</small></div></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <div class="form-card">
                    <div class="card-body-custom text-center py-5">
                        <i class="fas fa-university" style="font-size: 64px; color: #ccc;"></i>
                        <h4 class="mt-3">Select a Bank Account</h4>
                        <p class="text-muted">Please select a bank account from the dropdown to view its ledger</p>
                        <a href="bank_accounts.php" class="btn-submit" style="width: auto; padding: 10px 25px;">Manage Bank Accounts</a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    document.getElementById('bank_id').addEventListener('change', function() {
        if(this.value) {
            window.location.href = 'bank_book.php?bank_id=' + this.value;
        }
    });
</script>

<?php include('../includes/ft.php'); ?>
</body>
</html>