<?php
session_start();
require_once '../config/conn.php';

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

$student_id = $_SESSION['user_id'];

// Check if user already has an account
$check_stmt = $conn->prepare("SELECT id FROM student_bank_accounts WHERE student_id = ?");
$check_stmt->bind_param("i", $student_id);
$check_stmt->execute();
$check_result = $check_stmt->get_result();

// Handle adding a new account
if (isset($_POST['add_account'])) {
    // Validate CSRF token if you have one
    // if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    //     $_SESSION['error'] = "Invalid request";
    //     header("Location: bank_accounts.php");
    //     exit();
    // }

    // Check if account already exists
    if ($check_result->num_rows > 0) {
        $_SESSION['error'] = "You can only have one bank account";
        header("Location: bank_accounts.php");
        exit();
    }

    // Sanitize and validate inputs
    $bank_code = trim($_POST['bank_code']);
    $account_number = trim($_POST['account_number']);
    $account_name = trim($_POST['account_name']);
    $is_primary = 1; // Always primary since only one account is allowed

    // Get bank name from code
    $bank_name = "Unknown Bank";
    $bank_stmt = $conn->prepare("SELECT name FROM banks WHERE code = ?");
    $bank_stmt->bind_param("s", $bank_code);
    $bank_stmt->execute();
    $bank_result = $bank_stmt->get_result();
    if ($bank_result->num_rows > 0) {
        $bank_data = $bank_result->fetch_assoc();
        $bank_name = $bank_data['name'];
    }

    // Validate account number (10 digits for Nigerian banks)
    if (!preg_match('/^\d{10}$/', $account_number)) {
        $_SESSION['error'] = "Account number must be 10 digits";
        header("Location: bank_accounts.php");
        exit();
    }

    // Validate account name (basic check)
    if (strlen($account_name) < 2 || strlen($account_name) > 100) {
        $_SESSION['error'] = "Account name must be between 2-100 characters";
        header("Location: bank_accounts.php");
        exit();
    }

    // Insert new account with transaction for safety
    $conn->begin_transaction();
    
    try {
        $stmt = $conn->prepare("
            INSERT INTO student_bank_accounts 
            (student_id, bank_code, bank_name, account_number, account_name, is_primary, created_at)
            VALUES (?, ?, ?, ?, ?, ?, NOW())
        ");
        $stmt->bind_param(
            "issssi",
            $student_id,
            $bank_code,
            $bank_name,
            $account_number,
            $account_name,
            $is_primary
        );

        if ($stmt->execute()) {
            $_SESSION['success'] = "Bank account added successfully";
            $conn->commit();
        } else {
            throw new Exception("Failed to add bank account");
        }
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error'] = $e->getMessage();
    }

    header("Location: bank_accounts.php");
    exit();
}

// Handle deleting an account
if (isset($_POST['delete_account'])) {
    // Validate CSRF token if you have one
    // if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    //     $_SESSION['error'] = "Invalid request";
    //     header("Location: bank_accounts.php");
    //     exit();
    // }

    $account_id = (int)$_POST['account_id'];

    // Verify the account belongs to the user
    $verify_stmt = $conn->prepare("
        DELETE FROM student_bank_accounts 
        WHERE id = ? AND student_id = ?
    ");
    $verify_stmt->bind_param("ii", $account_id, $student_id);

    if ($verify_stmt->execute()) {
        $_SESSION['success'] = "Bank account deleted successfully";
    } else {
        $_SESSION['error'] = "Failed to delete bank account";
    }

    header("Location: bank_accounts.php");
    exit();
}

// Default redirect if no action matched
header("Location: bank_accounts.php");
exit();
?>