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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit;
}

try {
    // Validate required fields
    if (empty($_POST['bank_name'])) {
        throw new Exception('Bank name is required');
    }

    // Validate SWIFT code format if provided
    if (!empty($_POST['swift_code'])) {
        if (!preg_match('/^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$/', $_POST['swift_code'])) {
            throw new Exception('Invalid SWIFT code format');
        }
    }

    // Validate email if provided
    if (!empty($_POST['email'])) {
        if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            throw new Exception('Invalid email format');
        }
    }

    $conn->begin_transaction();

    try {
        if (empty($_POST['bank_code'])) {
            // Insert new bank
            $sql = "INSERT INTO banks (
                bank_name,
                bank_branch,
                swift_code,
                bank_address,
                contact_person,
                tel_no,
                email,
                active,
                user_id
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            $active = isset($_POST['active']) ? 1 : 0;
            
            $stmt->bind_param('sssssssii',
                $_POST['bank_name'],
                $_POST['bank_branch'],
                $_POST['swift_code'],
                $_POST['bank_address'],
                $_POST['contact_person'],
                $_POST['tel_no'],
                $_POST['email'],
                $active,
                $_SESSION['user_id']
            );

            if (!$stmt->execute()) {
                throw new Exception("Failed to save bank: " . $stmt->error);
            }

            $bank_code = $conn->insert_id;
            $message = 'Bank added successfully';
        } else {
            // Update existing bank
            $sql = "UPDATE banks SET 
                    bank_name = ?,
                    bank_branch = ?,
                    swift_code = ?,
                    bank_address = ?,
                    contact_person = ?,
                    tel_no = ?,
                    email = ?,
                    active = ?,
                    modified_by = ?
                    WHERE bank_code = ?";

            $stmt = $conn->prepare($sql);
            $active = isset($_POST['active']) ? 1 : 0;
            
            $stmt->bind_param('sssssssiis',
                $_POST['bank_name'],
                $_POST['bank_branch'],
                $_POST['swift_code'],
                $_POST['bank_address'],
                $_POST['contact_person'],
                $_POST['tel_no'],
                $_POST['email'],
                $active,
                $_SESSION['user_id'],
                $_POST['bank_code']
            );

            if (!$stmt->execute()) {
                throw new Exception("Failed to update bank: " . $stmt->error);
            }

            $bank_code = $_POST['bank_code'];
            $message = 'Bank updated successfully';
        }

        // Log activity
        $sql = "INSERT INTO activity_log (
            user_id, 
            action, 
            table_name,
            record_id,
            new_values,
            ip_address,
            user_agent,
            action_date
        ) VALUES (?, ?, 'banks', ?, ?, ?, ?, NOW())";

        $stmt = $conn->prepare($sql);
        $action = empty($_POST['bank_code']) ? 'CREATE' : 'UPDATE';
        $new_values = json_encode($_POST);

        $stmt->bind_param('ssssss',
            $_SESSION['user_id'],
            $action,
            $bank_code,
            $new_values,
            $_SERVER['REMOTE_ADDR'],
            $_SERVER['HTTP_USER_AGENT']
        );

        if (!$stmt->execute()) {
            throw new Exception("Failed to log activity");
        }

        $conn->commit();

        echo json_encode([
            'success' => true,
            'message' => $message
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>