<?php 
session_start();
if(!isset($_SESSION['admin_login'])) {
    header('location:adminlogin.php');
    exit;
}

// Set paths correctly using the directory of the current script
$db_path = __DIR__ . '/_inc/dbconn.php';
$func_path = __DIR__ . '/_inc/function.php';

// Check if files exist before requiring to prevent Fatal Errors
if (!file_exists($db_path)) {
    die("CRITICAL ERROR: Database connection file missing at: $db_path");
}
require $db_path;

if (!file_exists($func_path)) {
    if(!function_exists('sendTransactionAlert')){
        function sendTransactionAlert($u, $t, $a, $d, $r) { return false; }
    }
    $missing_func = true;
} else {
    require $func_path;
    $missing_func = false;
}

$show_alert = false;
$alert_type = "";
$alert_msg = "";

// --- PROCESSING LOGIC ---
if(isset($_POST['credit2'])) {
    $userId  = mysqli_real_escape_string($con, $_POST['account']);
    $amount  = mysqli_real_escape_string($con, $_POST['amount']);
    $date    = mysqli_real_escape_string($con, $_POST['tr_date']);
    $desc    = mysqli_real_escape_string($con, $_POST['tr_info']);
    $sendMail = isset($_POST['send_email']) ? true : false;
    $ref     = "CRD-" . strtoupper(bin2hex(random_bytes(4)));

    // 1. Update user balance
    $update = mysqli_query($con, "UPDATE users SET balance = balance + '$amount' WHERE id = '$userId'");

    if($update) {
        // 2. Log transaction - Explicitly marked as 'completed'
        mysqli_query($con, "INSERT INTO transactions (user_id, type, amount, description, reference_id, status, created_at) 
                           VALUES ('$userId', 'credit', '$amount', '$desc', '$ref', 'completed', '$date')");
        
        // 3. Optional Email Alert
        if($sendMail && !$missing_func) {
            sendTransactionAlert($userId, 'credit', $amount, $desc, $ref);
        }

        $show_alert = true;
        $alert_type = "success";
        $alert_msg = "Account Credited Successfully! The transaction is marked as COMPLETED.";
    } else {
        $show_alert = true;
        $alert_type = "error";
        $alert_msg = "Database Error: " . mysqli_error($con);
    }
}

include 'admin_header.php';
include 'admin_navbar.php';
?>

<?php if($show_alert): ?>
<div class="modal-overlay">
    <div class="alert-box">
        <div class="alert-icon <?php echo ($alert_type == 'success') ? 'icon-success' : 'icon-error'; ?>">
            <i class="mdi <?php echo ($alert_type == 'success') ? 'mdi-check-circle' : 'mdi-alert-circle'; ?>"></i>
        </div>
        <h2 style="font-weight: 800; color: #121212;"><?php echo ($alert_type == 'success') ? 'Success!' : 'Error Occurred'; ?></h2>
        <p style="color: #64748B; margin: 15px 0;"><?php echo $alert_msg; ?></p>
        <button class="alert-btn" onclick="window.location.href='credit.php'" style="width:100%; padding: 12px; background: var(--primary-red); color: white; border:none; border-radius: 10px; cursor:pointer; font-weight:700;">
            Continue & Refresh
        </button>
    </div>
</div>
<?php endif; ?>

<div class="main-wrapper">
    <header>
        <div class="menu-toggle" id="menuBtn">
            <i class="mdi mdi-menu"></i>
        </div>
        <div class="user-info">
            <span>Welcome, Admin</span>
            <i class="mdi mdi-account-circle" style="font-size: 2rem; color: var(--primary-red);"></i>
        </div>
    </header>

    <main class="content">
        <div class="welcome-banner">
            <h2>Credit Operations</h2>
            <p>Manually deposit funds into a customer's account ledger.</p>
        </div>

        <?php if($missing_func): ?>
            <div style="background: #fff3cd; color: #856404; padding: 15px; border-radius: 12px; border-left: 5px solid #ffeeba; margin-bottom: 25px; font-size: 0.9rem;">
                <i class="mdi mdi-alert"></i> <strong>Maintenance Note:</strong> Email notifications are currently disabled.
            </div>
        <?php endif; ?>

        <div class="funding-card" style="background: white; border-radius: 24px; box-shadow: 0 15px 35px rgba(0,0,0,0.05); border: 1px solid #eee; overflow: hidden; max-width: 800px; margin: 0 auto;">
            
            <div style="background: linear-gradient(135deg, #121212 0%, #333 100%); padding: 40px; text-align: center; color: white;">
                <div style="width: 70px; height: 70px; background: rgba(230, 57, 70, 0.1); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px;">
                    <i class="mdi mdi-bank-plus" style="font-size: 2.5rem; color: var(--primary-red);"></i>
                </div>
                <h3 style="font-weight: 700; letter-spacing: -0.5px;">Deposit Funds</h3>
                <p style="opacity: 0.7; font-size: 0.9rem;">Update account balance and log transaction</p>
            </div>

            <div style="padding: 40px;">
                <form action="" method="POST">
                    
                    <div style="margin-bottom: 25px;">
                        <label style="display: block; font-weight: 700; color: #121212; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 10px;">Select Recipient Account</label>
                        <select class="form-control" name="account" required style="width: 100%; height: 55px; border-radius: 12px; border: 2px solid #f1f5f9; padding: 0 20px; font-weight: 500; color: #333;">
                            <option value="" disabled selected>Search customer...</option>
                            <?php 
                            $sql = "SELECT id, fullname, account_number FROM users ORDER BY fullname ASC";
                            $result = mysqli_query($con, $sql);
                            while($row = mysqli_fetch_assoc($result)){
                                echo '<option value="'.$row['id'].'">'.htmlspecialchars($row['fullname']).' ('.$row['account_number'].')</option>';
                            }
                            ?>
                        </select>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin-bottom: 25px;">
                        <div>
                            <label style="display: block; font-weight: 700; color: #121212; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 10px;">Amount ($)</label>
                            <input type="number" class="form-control" name="amount" placeholder="0.00" step="0.01" required style="width: 100%; height: 55px; border-radius: 12px; border: 2px solid #f1f5f9; padding: 0 20px; font-weight: 600; font-size: 1.1rem; color: #121212;">
                        </div>
                        <div>
                            <label style="display: block; font-weight: 700; color: #121212; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 10px;">Value Date</label>
                            <input type="date" class="form-control" name="tr_date" value="<?php echo date('Y-m-d'); ?>" required style="width: 100%; height: 55px; border-radius: 12px; border: 2px solid #f1f5f9; padding: 0 20px; color: #333;">
                        </div>
                    </div>

                    <div style="margin-bottom: 25px;">
                        <label style="display: block; font-weight: 700; color: #121212; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 10px;">Transaction Narration</label>
                        <textarea class="form-control" name="tr_info" rows="3" placeholder="Enter purpose of funding..." style="width: 100%; border-radius: 12px; border: 2px solid #f1f5f9; padding: 15px 20px; font-weight: 400; color: #333; resize: none;"></textarea>
                    </div>

                    <div style="background: #f8fafc; padding: 20px; border-radius: 15px; display: flex; align-items: center; justify-content: space-between; border: 1px solid #edf2f7;">
                        <div>
                            <p style="font-weight: 700; margin: 0; font-size: 0.9rem; color: #121212;">Send Email Notification</p>
                            <small style="color: #718096;">Inform customer of this credit alert instantly</small>
                        </div>
                        <input type="checkbox" name="send_email" value="1" <?php echo $missing_func ? 'disabled' : 'checked'; ?> style="width: 20px; height: 20px; cursor: pointer; accent-color: var(--primary-red);">
                    </div>

                    <button type="submit" name="credit2" class="authorize-btn" style="width: 100%; margin-top: 35px; background: var(--primary-red); height: 60px; color: white; border:none; border-radius:12px; font-weight:700; font-size: 1rem; letter-spacing: 1px; text-transform: uppercase; cursor:pointer; transition: 0.3s;">
                        <i class="mdi mdi-check-decagram-outline" style="margin-right: 8px;"></i> Authorize Deposit
                    </button>
                </form>
            </div>
        </div>
    </main>
</div>

<style>
    /* Focus effects for Professional look */
    .form-control:focus {
        outline: none;
        border-color: var(--primary-red) !important;
        box-shadow: 0 0 0 4px rgba(230, 57, 70, 0.05);
    }
    .authorize-btn:hover {
        background-color: #c1121f !important;
        transform: translateY(-2px);
    }
    .modal-overlay {
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.8); backdrop-filter: blur(5px);
        display: flex; align-items: center; justify-content: center; z-index: 9999;
    }
    .alert-box {
        background: white; padding: 40px; border-radius: 20px; text-align: center;
        max-width: 450px; width: 90%; box-shadow: 0 25px 50px rgba(0,0,0,0.3);
    }
    .alert-icon { font-size: 60px; margin-bottom: 15px; }
    .icon-success { color: #10b981; }
    .icon-error { color: #e63946; }
</style>

<?php include 'admin_footer.php'; ?>
