<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Check if user has permission to add transactions (Admin or Fund Manager)
if (!in_array($role_name, ['Administrator', 'Fund Manager'])) {
    header('Location: index.php');
    exit();
}

// Handle form submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fund_id = $_POST['fund_id'];
    $contributor_id = $_POST['contributor_id'];
    $transaction_type = $_POST['transaction_type'];
    $amount = floatval($_POST['amount']);
    $transaction_date = $_POST['transaction_date'];
    $payment_method = $_POST['payment_method'];
    $reference_number = trim($_POST['reference_number']);
    $description = trim($_POST['description']);
    $purpose = trim($_POST['purpose']);
    $expected_return_date = !empty($_POST['expected_return_date']) ? $_POST['expected_return_date'] : null;
    $interest_rate = !empty($_POST['interest_rate']) ? floatval($_POST['interest_rate']) : 0.00;
    $notes = trim($_POST['notes']);
    
    // Validation
    $errors = [];
    
    if (empty($fund_id)) {
        $errors[] = "Fund is required";
    }
    
    if (empty($contributor_id)) {
        $errors[] = "Contributor is required";
    }
    
    if ($amount <= 0) {
        $errors[] = "Amount must be greater than 0";
    }
    
    if (empty($transaction_date)) {
        $errors[] = "Transaction date is required";
    }
    
    // Additional validation for withdrawals
    if ($transaction_type === 'WITHDRAWAL') {
        // Check if fund has sufficient balance
        $balance_check = $conn->prepare("SELECT current_balance FROM funds WHERE fund_id = ?");
        $balance_check->bind_param("i", $fund_id);
        $balance_check->execute();
        $fund_balance = $balance_check->get_result()->fetch_assoc()['current_balance'];
        
        if ($amount > $fund_balance) {
            $errors[] = "Insufficient fund balance. Available: KES " . number_format($fund_balance);
        }
        
        // Check if contributor has sufficient balance
        $contributor_balance_check = $conn->prepare("SELECT current_balance FROM contributors WHERE contributor_id = ?");
        $contributor_balance_check->bind_param("i", $contributor_id);
        $contributor_balance_check->execute();
        $contributor_balance = $contributor_balance_check->get_result()->fetch_assoc()['current_balance'];
        
        if ($amount > $contributor_balance) {
            $errors[] = "Contributor has insufficient balance. Available: KES " . number_format($contributor_balance);
        }
    }
    
    if (empty($errors)) {
        try {
            $conn->begin_transaction();
            
            // Generate transaction number
            $transaction_number = 'TXN' . date('Ymd') . sprintf('%04d', rand(1000, 9999));
            
            // Check if transaction number exists
            $check_txn = $conn->prepare("SELECT transaction_id FROM fund_transactions WHERE transaction_number = ?");
            $check_txn->bind_param("s", $transaction_number);
            $check_txn->execute();
            while ($check_txn->get_result()->num_rows > 0) {
                $transaction_number = 'TXN' . date('Ymd') . sprintf('%04d', rand(1000, 9999));
                $check_txn->bind_param("s", $transaction_number);
                $check_txn->execute();
            }
            
            // Insert transaction
            $insert_query = "INSERT INTO fund_transactions (
                transaction_number, fund_id, contributor_id, transaction_type, amount, 
                transaction_date, payment_method, reference_number, description, purpose,
                expected_return_date, interest_rate, status, processed_by, notes
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'COMPLETED', ?, ?)";
            
            $stmt = $conn->prepare($insert_query);
            $stmt->bind_param("siisdssssssdis", 
                $transaction_number, $fund_id, $contributor_id, $transaction_type, $amount,
                $transaction_date, $payment_method, $reference_number, $description, $purpose,
                $expected_return_date, $interest_rate, $user_id, $notes
            );
            
            if ($stmt->execute()) {
                // FIXED: Get insert_id from connection, not from statement
                $transaction_id = $conn->insert_id;
                
                // Update fund balance based on transaction type
                if ($transaction_type === 'CONTRIBUTION') {
                    $update_fund = $conn->prepare("UPDATE funds SET 
                        current_balance = current_balance + ?,
                        total_contributions = total_contributions + ?
                        WHERE fund_id = ?");
                    $update_fund->bind_param("ddi", $amount, $amount, $fund_id);
                    $update_fund->execute();
                    
                    // Update contributor balance
                    $update_contributor = $conn->prepare("UPDATE contributors SET 
                        total_contributed = total_contributed + ?,
                        current_balance = current_balance + ?
                        WHERE contributor_id = ?");
                    $update_contributor->bind_param("ddi", $amount, $amount, $contributor_id);
                    $update_contributor->execute();
                    
                } elseif ($transaction_type === 'WITHDRAWAL') {
                    $update_fund = $conn->prepare("UPDATE funds SET 
                        current_balance = current_balance - ?,
                        total_withdrawals = total_withdrawals + ?
                        WHERE fund_id = ?");
                    $update_fund->bind_param("ddi", $amount, $amount, $fund_id);
                    $update_fund->execute();
                    
                    // Update contributor balance
                    $update_contributor = $conn->prepare("UPDATE contributors SET 
                        total_withdrawn = total_withdrawn + ?,
                        current_balance = current_balance - ?
                        WHERE contributor_id = ?");
                    $update_contributor->bind_param("ddi", $amount, $amount, $contributor_id);
                    $update_contributor->execute();
                }
                
                // Log activity
                $activity_query = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address) 
                                   VALUES (?, 'CREATE', 'TRANSACTIONS', ?, 'TRANSACTION', ?, ?)";
                $activity_stmt = $conn->prepare($activity_query);
                $new_values = json_encode([
                    'transaction_number' => $transaction_number,
                    'transaction_type' => $transaction_type,
                    'amount' => $amount,
                    'fund_id' => $fund_id,
                    'contributor_id' => $contributor_id
                ]);
                $ip_address = $_SERVER['REMOTE_ADDR'];
                $activity_stmt->bind_param("iiss", $user_id, $transaction_id, $new_values, $ip_address);
                $activity_stmt->execute();
                
                $conn->commit();
                
                $message = "Transaction '$transaction_number' added successfully!";
                $message_type = "success";
                
                // Clear form data on success
                $_POST = [];
                
            } else {
                throw new Exception("Error adding transaction: " . $conn->error);
            }
            
        } catch (Exception $e) {
            $conn->rollback();
            $message = "Error: " . $e->getMessage();
            $message_type = "error";
        }
    } else {
        $message = implode(", ", $errors);
        $message_type = "error";
    }
}

// Get funds for dropdown
$funds_query = "SELECT f.fund_id, f.fund_name, f.fund_code, f.current_balance 
                FROM funds f 
                WHERE f.is_active = 1 AND f.status = 'ACTIVE' 
                ORDER BY f.fund_name";
$funds_result = $conn->query($funds_query);

// Get contributors for dropdown
$contributors_query = "SELECT c.contributor_id, c.contributor_number, 
                       CONCAT(c.first_name, ' ', c.last_name) as full_name,
                       c.current_balance, c.relationship
                       FROM contributors c 
                       WHERE c.is_active = 1 
                       ORDER BY c.first_name, c.last_name";
$contributors_result = $conn->query($contributors_query);

// Get statistics for display
$stats_query = "SELECT 
    COUNT(*) as total_transactions,
    SUM(CASE WHEN transaction_type = 'CONTRIBUTION' THEN amount ELSE 0 END) as total_contributions,
    SUM(CASE WHEN transaction_type = 'WITHDRAWAL' THEN amount ELSE 0 END) as total_withdrawals,
    COUNT(CASE WHEN transaction_date = CURDATE() THEN 1 END) as today_transactions
    FROM fund_transactions 
    WHERE status = 'COMPLETED'";
$stats = $conn->query($stats_query)->fetch_assoc();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Transaction - Personal Fund Tracker')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling from previous pages */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Breadcrumb */
        .breadcrumb-card {
            background: white;
            border-radius: 8px;
            padding: 1rem 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .breadcrumb {
            margin: 0;
            background: none;
            padding: 0;
        }
        
        .breadcrumb-item a {
            color: #3b82f6;
            text-decoration: none;
        }
        
        .breadcrumb-item.active {
            color: #64748b;
        }
        
        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Form Card */
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .form-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .form-section {
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-size: 1rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .section-title i {
            color: #059669;
        }
        
        /* Form Controls */
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select, .form-control:focus, .form-select:focus {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .form-text {
            color: #64748b;
            font-size: 0.75rem;
            margin-top: 0.25rem;
        }
        
        /* Required field indicator */
        .required {
            color: #dc2626;
        }
        
        /* Buttons */
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-success {
            background: #059669;
            color: white;
        }
        
        .btn-success:hover {
            background: #047857;
            color: white;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
        }
        
        /* Input Groups */
        .input-group-text {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            color: #64748b;
            font-weight: 500;
        }
        
        /* Balance Display */
        .balance-display {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            padding: 0.5rem;
            font-size: 0.875rem;
            margin-top: 0.5rem;
        }
        
        .balance-display.positive {
            color: #059669;
            background: #dcfce7;
            border-color: #059669;
        }
        
        .balance-display.negative {
            color: #dc2626;
            background: #fee2e2;
            border-color: #dc2626;
        }
        
        /* Transaction Type Styling */
        .transaction-type-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            cursor: pointer;
            transition: all 0.2s ease;
            text-align: center;
        }
        
        .transaction-type-card:hover {
            border-color: #3b82f6;
            background: #f8fafc;
        }
        
        .transaction-type-card.selected {
            border-color: #059669;
            background: #dcfce7;
        }
        
        /* Button Group */
        .button-group {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            padding-top: 1.5rem;
            border-top: 1px solid #e2e8f0;
            margin-top: 2rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .button-group {
                flex-direction: column;
            }
            
            .form-card {
                padding: 1.5rem;
            }
        }
        
        /* Footer spacing fix */
        .main-content {
            padding-bottom: 2rem;
        }
        
        .page-content {
            margin-bottom: 3rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Add New Transaction</h1>
                        <p class="page-subtitle">Record contributions, withdrawals, and other fund transactions</p>
                    </div>

                    <!-- Breadcrumb -->
                    <div class="breadcrumb-card">
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                <li class="breadcrumb-item"><a href="list_transactions.php">All Transactions</a></li>
                                <li class="breadcrumb-item active">Add Transaction</li>
                            </ol>
                        </nav>
                    </div>

                    <!-- Current System Stats -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_transactions'] ?? 0; ?></div>
                            <div class="stat-label">Total Transactions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_contributions'] ?? 0); ?></div>
                            <div class="stat-label">Total Contributions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_withdrawals'] ?? 0); ?></div>
                            <div class="stat-label">Total Withdrawals</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['today_transactions'] ?? 0; ?></div>
                            <div class="stat-label">Today's Transactions</div>
                        </div>
                    </div>

                    <!-- Add Transaction Form -->
                    <div class="form-card">
                        <h3 class="form-title">Transaction Details</h3>
                        
                        <form method="POST" id="addTransactionForm">
                            <!-- Basic Transaction Information -->
                            <div class="form-section">
                                <h4 class="section-title">
                                    <i class="ph-currency-circle-dollar"></i>
                                    Basic Information
                                </h4>
                                
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Fund <span class="required">*</span></label>
                                        <select class="form-select" name="fund_id" required id="fundSelect">
                                            <option value="">Select a fund</option>
                                            <?php while ($fund = $funds_result->fetch_assoc()): ?>
                                                <option value="<?php echo $fund['fund_id']; ?>" 
                                                        data-balance="<?php echo $fund['current_balance']; ?>"
                                                        <?php echo (($_POST['fund_id'] ?? '') == $fund['fund_id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($fund['fund_name']); ?> (<?php echo $fund['fund_code']; ?>)
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                        <div id="fundBalance" class="balance-display" style="display: none;">
                                            Available Balance: KES <span id="fundBalanceAmount">0</span>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Contributor <span class="required">*</span></label>
                                        <select class="form-select" name="contributor_id" required id="contributorSelect">
                                            <option value="">Select a contributor</option>
                                            <?php while ($contributor = $contributors_result->fetch_assoc()): ?>
                                                <option value="<?php echo $contributor['contributor_id']; ?>" 
                                                        data-balance="<?php echo $contributor['current_balance']; ?>"
                                                        <?php echo (($_POST['contributor_id'] ?? '') == $contributor['contributor_id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($contributor['full_name']); ?> (<?php echo $contributor['contributor_number']; ?>)
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                        <div id="contributorBalance" class="balance-display" style="display: none;">
                                            Contributor Balance: KES <span id="contributorBalanceAmount">0</span>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Transaction Type <span class="required">*</span></label>
                                        <select class="form-select" name="transaction_type" required id="transactionType">
                                            <option value="">Select transaction type</option>
                                            <option value="CONTRIBUTION" <?php echo (($_POST['transaction_type'] ?? '') == 'CONTRIBUTION') ? 'selected' : ''; ?>>Contribution</option>
                                            <option value="WITHDRAWAL" <?php echo (($_POST['transaction_type'] ?? '') == 'WITHDRAWAL') ? 'selected' : ''; ?>>Withdrawal</option>
                                            <option value="TRANSFER_IN" <?php echo (($_POST['transaction_type'] ?? '') == 'TRANSFER_IN') ? 'selected' : ''; ?>>Transfer In</option>
                                            <option value="TRANSFER_OUT" <?php echo (($_POST['transaction_type'] ?? '') == 'TRANSFER_OUT') ? 'selected' : ''; ?>>Transfer Out</option>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Amount <span class="required">*</span></label>
                                        <div class="input-group">
                                            <span class="input-group-text">KES</span>
                                            <input type="number" class="form-control" name="amount" required min="0" step="0.01"
                                                   placeholder="0.00" value="<?php echo htmlspecialchars($_POST['amount'] ?? ''); ?>" id="amountInput">
                                        </div>
                                        <div id="amountValidation" class="form-text"></div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Transaction Date <span class="required">*</span></label>
                                        <input type="date" class="form-control" name="transaction_date" required 
                                               value="<?php echo htmlspecialchars($_POST['transaction_date'] ?? date('Y-m-d')); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Payment Method</label>
                                        <select class="form-select" name="payment_method">
                                            <option value="CASH" <?php echo (($_POST['payment_method'] ?? 'CASH') == 'CASH') ? 'selected' : ''; ?>>Cash</option>
                                            <option value="BANK_TRANSFER" <?php echo (($_POST['payment_method'] ?? '') == 'BANK_TRANSFER') ? 'selected' : ''; ?>>Bank Transfer</option>
                                            <option value="MPESA" <?php echo (($_POST['payment_method'] ?? '') == 'MPESA') ? 'selected' : ''; ?>>M-Pesa</option>
                                            <option value="MOBILE_MONEY" <?php echo (($_POST['payment_method'] ?? '') == 'MOBILE_MONEY') ? 'selected' : ''; ?>>Mobile Money</option>
                                            <option value="CHEQUE" <?php echo (($_POST['payment_method'] ?? '') == 'CHEQUE') ? 'selected' : ''; ?>>Cheque</option>
                                            <option value="OTHER" <?php echo (($_POST['payment_method'] ?? '') == 'OTHER') ? 'selected' : ''; ?>>Other</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Additional Details Section -->
                            <div class="form-section">
                                <h4 class="section-title">
                                    <i class="ph-info"></i>
                                    Additional Details
                                </h4>
                                
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Reference Number</label>
                                        <input type="text" class="form-control" name="reference_number" 
                                               placeholder="Transaction reference/receipt number" 
                                               value="<?php echo htmlspecialchars($_POST['reference_number'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Interest Rate (%)</label>
                                        <input type="number" class="form-control" name="interest_rate" min="0" max="100" step="0.01"
                                               placeholder="0.00" value="<?php echo htmlspecialchars($_POST['interest_rate'] ?? ''); ?>">
                                        <div class="form-text">For loans or investments</div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Expected Return Date</label>
                                        <input type="date" class="form-control" name="expected_return_date" 
                                               value="<?php echo htmlspecialchars($_POST['expected_return_date'] ?? ''); ?>">
                                        <div class="form-text">For temporary contributions or loans</div>
                                    </div>
                                    
                                    <div class="col-12">
                                        <label class="form-label">Description</label>
                                        <input type="text" class="form-control" name="description" 
                                               placeholder="Brief description of the transaction" 
                                               value="<?php echo htmlspecialchars($_POST['description'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-12">
                                        <label class="form-label">Purpose</label>
                                        <textarea class="form-control" name="purpose" rows="3" 
                                                  placeholder="Detailed purpose or reason for the transaction"><?php echo htmlspecialchars($_POST['purpose'] ?? ''); ?></textarea>
                                    </div>
                                    
                                    <div class="col-12">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="notes" rows="3" 
                                                  placeholder="Any additional notes or comments"><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                                    <div class="col-12">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="notes" rows="3" 
                                                  placeholder="Any additional notes or comments"><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                                        <div class="form-text">Internal notes (not visible to contributors)</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Form Buttons -->
                            <div class="button-group">
                                <a href="list_transactions.php" class="btn btn-outline-secondary">
                                    <i class="ph-x"></i> Cancel
                                </a>
                                <button type="submit" class="btn btn-success">
                                    <i class="ph-plus"></i> Add Transaction
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <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>
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Show SweetAlert messages if present
            <?php if ($message): ?>
                Swal.fire({
                    title: '<?php echo $message_type === "success" ? "Success!" : "Error!"; ?>',
                    text: '<?php echo addslashes($message); ?>',
                    icon: '<?php echo $message_type === "success" ? "success" : "error"; ?>',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#059669'
                }).then((result) => {
                    <?php if ($message_type === "success"): ?>
                        // Optionally redirect to transactions list or clear form
                        window.location.href = 'list_transactions.php';
                    <?php endif; ?>
                });
            <?php endif; ?>
            
            // Fund selection - show balance
            $('#fundSelect').on('change', function() {
                const selectedOption = $(this).find('option:selected');
                const balance = selectedOption.data('balance');
                
                if (selectedOption.val()) {
                    $('#fundBalanceAmount').text(Number(balance).toLocaleString());
                    $('#fundBalance').show().addClass(balance > 0 ? 'positive' : 'negative');
                    validateAmount();
                } else {
                    $('#fundBalance').hide();
                }
            });
            
            // Contributor selection - show balance
            $('#contributorSelect').on('change', function() {
                const selectedOption = $(this).find('option:selected');
                const balance = selectedOption.data('balance');
                
                if (selectedOption.val()) {
                    $('#contributorBalanceAmount').text(Number(balance).toLocaleString());
                    $('#contributorBalance').show().addClass(balance > 0 ? 'positive' : 'negative');
                    validateAmount();
                } else {
                    $('#contributorBalance').hide();
                }
            });
            
            // Transaction type change
            $('#transactionType').on('change', function() {
                validateAmount();
                updateFormBasedOnType();
            });
            
            // Amount input validation
            $('#amountInput').on('input', function() {
                validateAmount();
            });
            
            function validateAmount() {
                const amount = parseFloat($('#amountInput').val()) || 0;
                const transactionType = $('#transactionType').val();
                const fundBalance = parseFloat($('#fundSelect option:selected').data('balance')) || 0;
                const contributorBalance = parseFloat($('#contributorSelect option:selected').data('balance')) || 0;
                
                let validationMessage = '';
                let isValid = true;
                
                if (amount <= 0) {
                    validationMessage = 'Amount must be greater than 0';
                    isValid = false;
                } else if (transactionType === 'WITHDRAWAL') {
                    if (amount > fundBalance) {
                        validationMessage = `Insufficient fund balance. Available: KES ${fundBalance.toLocaleString()}`;
                        isValid = false;
                    } else if (amount > contributorBalance) {
                        validationMessage = `Contributor has insufficient balance. Available: KES ${contributorBalance.toLocaleString()}`;
                        isValid = false;
                    }
                }
                
                $('#amountValidation').text(validationMessage).css('color', isValid ? '#059669' : '#dc2626');
                $('#amountInput').toggleClass('is-invalid', !isValid);
                
                return isValid;
            }
            
            function updateFormBasedOnType() {
                const transactionType = $('#transactionType').val();
                
                // Update labels and placeholders based on transaction type
                if (transactionType === 'WITHDRAWAL') {
                    $('label[for="amountInput"]').html('Withdrawal Amount <span class="required">*</span>');
                    $('#amountInput').attr('placeholder', 'Amount to withdraw');
                } else if (transactionType === 'CONTRIBUTION') {
                    $('label[for="amountInput"]').html('Contribution Amount <span class="required">*</span>');
                    $('#amountInput').attr('placeholder', 'Amount to contribute');
                } else {
                    $('label[for="amountInput"]').html('Amount <span class="required">*</span>');
                    $('#amountInput').attr('placeholder', 'Transaction amount');
                }
            }
            
            // Form validation and submission
            $('#addTransactionForm').on('submit', function(e) {
                e.preventDefault();
                
                let isValid = true;
                let errorMessages = [];
                
                // Check required fields
                $(this).find('input[required], select[required]').each(function() {
                    if (!$(this).val().trim()) {
                        $(this).addClass('is-invalid');
                        isValid = false;
                        errorMessages.push($(this).prev('label').text().replace('*', '').trim() + ' is required');
                    } else {
                        $(this).removeClass('is-invalid');
                    }
                });
                
                // Validate amount
                if (!validateAmount()) {
                    isValid = false;
                    errorMessages.push('Please check the transaction amount');
                }
                
                if (!isValid) {
                    Swal.fire({
                        title: 'Validation Error!',
                        html: 'Please fix the following issues:<br>• ' + errorMessages.join('<br>• '),
                        icon: 'error',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#dc2626'
                    });
                    return false;
                }
                
                // Show confirmation dialog
                const transactionType = $('#transactionType').val();
                const amount = parseFloat($('#amountInput').val());
                const fundName = $('#fundSelect option:selected').text();
                const contributorName = $('#contributorSelect option:selected').text();
                
                Swal.fire({
                    title: 'Confirm Transaction',
                    html: `
                        <div style="text-align: left; padding: 1rem;">
                            <p><strong>Type:</strong> ${transactionType}</p>
                            <p><strong>Amount:</strong> KES ${amount.toLocaleString()}</p>
                            <p><strong>Fund:</strong> ${fundName}</p>
                            <p><strong>Contributor:</strong> ${contributorName}</p>
                        </div>
                    `,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Process Transaction',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#059669',
                    cancelButtonColor: '#6b7280'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Show loading
                        Swal.fire({
                            title: 'Processing Transaction...',
                            text: 'Please wait while we process your transaction.',
                            icon: 'info',
                            allowOutsideClick: false,
                            showConfirmButton: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });
                        
                        // Submit the form
                        this.submit();
                    }
                });
            });
            
            // Initialize form
            $('#fundSelect').trigger('change');
            $('#contributorSelect').trigger('change');
            $('#transactionType').trigger('change');
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>