<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'system_admin'])) {
    header("Location: login.php");
    exit();
}

// Check if user is system administrator
$is_system_admin = false;
if (isset($_SESSION['role']) && $_SESSION['role'] == 'system_admin') {
    $is_system_admin = true;
} else {
    // Check database for role
    include '../includes/db.php';
    $email = $_SESSION['email'] ?? '';
    $check = $conn->query("SELECT role FROM users WHERE email='$email'");
    if($check->num_rows > 0) {
        $role = $check->fetch_assoc()['role'];
        if($role == 'system_admin') {
            $is_system_admin = true;
            $_SESSION['role'] = 'system_admin'; // Update session
        }
    }
}

if (!$is_system_admin) {
    echo "<div style='padding: 50px; text-align: center;'>
            <h2 style='color: #d32f2f;'>Access Denied</h2>
            <p>Only System Administrators can access Payment Options management.</p>
            <a href='index.php' class='btn-primary' style='display: inline-block; padding: 10px 20px; text-decoration: none;'>Back to Dashboard</a>
          </div>";
    include 'includes/footer.php';
    exit();
}

include '../includes/db.php';
include 'includes/header.php';

$message = "";

// Handle Edit Payment Option
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_option'])) {
    $id = intval($_POST['id']);
    $bank_name = $conn->real_escape_string($_POST['bank_name']);
    $account_title = $conn->real_escape_string($_POST['account_title']);
    $account_number = $conn->real_escape_string($_POST['account_number']);
    $branch_code = $conn->real_escape_string($_POST['branch_code']);

    $sql = "UPDATE payment_options SET bank_name='$bank_name', account_title='$account_title', account_number='$account_number', branch_code='$branch_code' WHERE id=$id";
    
    if ($conn->query($sql) === TRUE) {
        $message = "Payment option updated successfully!";
    } else {
        $message = "Error updating option: " . $conn->error;
    }
}

// Handle Add Payment Option
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_option'])) {
    $bank_name = $conn->real_escape_string($_POST['bank_name']);
    $account_title = $conn->real_escape_string($_POST['account_title']);
    $account_number = $conn->real_escape_string($_POST['account_number']);
    $branch_code = $conn->real_escape_string($_POST['branch_code']);

    $sql = "INSERT INTO payment_options (bank_name, account_title, account_number, branch_code) 
            VALUES ('$bank_name', '$account_title', '$account_number', '$branch_code')";
    
    if ($conn->query($sql) === TRUE) {
        $message = "Payment option added successfully!";
    } else {
        $message = "Error adding option: " . $conn->error;
    }
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $sql = "DELETE FROM payment_options WHERE id = $id";
    if ($conn->query($sql) === TRUE) {
        $message = "Payment option deleted successfully!";
    } else {
        $message = "Error deleting option.";
    }
}

// Handle Edit Form Display
$edit_mode = false;
$edit_data = [];
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $edit_result = $conn->query("SELECT * FROM payment_options WHERE id = $id");
    if ($edit_result->num_rows > 0) {
        $edit_data = $edit_result->fetch_assoc();
        $edit_mode = true;
    }
}

// Fetch Options
$sql = "SELECT * FROM payment_options ORDER BY created_at DESC";
$result = $conn->query($sql);
?>

<div class="dashboard-container">
    <div class="sidebar admin-sidebar">
        <?php include 'includes/sidebar.php'; ?>
    </div>

    <div class="main-content">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Manage Payment Options</h3>
            </div>
            
            <?php if($message): ?>
                <div class="alert alert-success"><?php echo $message; ?></div>
            <?php endif; ?>

            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 30px; border: 1px solid #ddd;">
                <h4 style="margin-top: 0;"><?php echo $edit_mode ? 'Edit Bank Account' : 'Add New Bank Account'; ?></h4>
                <form method="POST" action="">
                    <input type="hidden" name="<?php echo $edit_mode ? 'edit_option' : 'add_option'; ?>" value="1">
                    <?php if($edit_mode): ?>
                        <input type="hidden" name="id" value="<?php echo $edit_data['id']; ?>">
                    <?php endif; ?>
                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                        <div class="form-group" style="flex: 1;">
                            <label>Bank Name</label>
                            <input type="text" name="bank_name" class="form-control" required placeholder="e.g. HBL" 
                                   value="<?php echo $edit_mode ? $edit_data['bank_name'] : ''; ?>">
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Account Title</label>
                            <input type="text" name="account_title" class="form-control" required placeholder="e.g. University of Lahore" 
                                   value="<?php echo $edit_mode ? $edit_data['account_title'] : ''; ?>">
                        </div>
                    </div>
                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                        <div class="form-group" style="flex: 1;">
                            <label>Account Number</label>
                            <input type="text" name="account_number" class="form-control" required 
                                   value="<?php echo $edit_mode ? $edit_data['account_number'] : ''; ?>">
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Branch Code</label>
                            <input type="text" name="branch_code" class="form-control" placeholder="Optional" 
                                   value="<?php echo $edit_mode ? $edit_data['branch_code'] : ''; ?>">
                        </div>
                    </div>
                    <button type="submit" class="btn-primary"><?php echo $edit_mode ? 'Update Account' : 'Add Account'; ?></button>
                    <?php if($edit_mode): ?>
                        <a href="payment_options.php" class="btn-outline" style="margin-left: 10px; text-decoration: none; padding: 8px 20px;">Cancel</a>
                    <?php endif; ?>
                </form>
            </div>

            <table>
                <thead>
                    <tr>
                        <th>Bank Name</th>
                        <th>Account Title</th>
                        <th>Account Number</th>
                        <th>Branch Code</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $row['bank_name']; ?></td>
                            <td><?php echo $row['account_title']; ?></td>
                            <td><?php echo $row['account_number']; ?></td>
                            <td><?php echo $row['branch_code']; ?></td>
                            <td>
                                <a href="payment_options.php?edit=<?php echo $row['id']; ?>" style="color: #2196f3; margin-right: 10px;">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="payment_options.php?delete=<?php echo $row['id']; ?>" onclick="return confirm('Are you sure?');" style="color: #d32f2f;">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" class="text-center">No payment options found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
