<?php
// school_admission/public/admin_edit_branch.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth_check.php';

requireRole(['super_admin']); // Only Super Admin can access this page

$message = '';
$branch_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$branch = null;

if ($branch_id === 0) {
    $_SESSION['message'] = "<div class='message error'>Invalid branch ID.</div>";
    redirect('admin_manage_branches.php');
}

// Fetch existing branch data
$stmt = $conn->prepare("SELECT branch_id, branch_name, location, contact_person, contact_email, contact_phone FROM branches WHERE branch_id = ?");
$stmt->bind_param("i", $branch_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $branch = $result->fetch_assoc();
} else {
    $_SESSION['message'] = "<div class='message error'>Branch not found.</div>";
    redirect('admin_manage_branches.php');
}
$stmt->close();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $branch_name = sanitize_input($_POST['branch_name']);
    $location = sanitize_input($_POST['location']);
    $contact_person = sanitize_input($_POST['contact_person']);
    $contact_email = sanitize_input($_POST['contact_email']);
    $contact_phone = sanitize_input($_POST['contact_phone']);

    if (empty($branch_name) || empty($location) || empty($contact_person) || empty($contact_email) || empty($contact_phone)) {
        $message = "<div class='message error'>All fields are required.</div>";
    } else {
        // Check if another branch name already exists (excluding current branch)
        $stmt_check = $conn->prepare("SELECT branch_id FROM branches WHERE branch_name = ? AND branch_id != ?");
        $stmt_check->bind_param("si", $branch_name, $branch_id);
        $stmt_check->execute();
        $stmt_check->store_result();

        if ($stmt_check->num_rows > 0) {
            $message = "<div class='message error'>A branch with this name already exists.</div>";
        } else {
            $stmt_update = $conn->prepare("UPDATE branches SET branch_name = ?, location = ?, contact_person = ?, contact_email = ?, contact_phone = ? WHERE branch_id = ?");
            $stmt_update->bind_param("sssssi", $branch_name, $location, $contact_person, $contact_email, $contact_phone, $branch_id);

            if ($stmt_update->execute()) {
                $_SESSION['message'] = "<div class='message success'>Branch updated successfully!</div>";
                redirect('admin_manage_branches.php');
            } else {
                $message = "<div class='message error'>Error updating branch: " . $stmt_update->error . "</div>";
            }
            $stmt_update->close();
        }
        $stmt_check->close();
    }
}

include __DIR__ . '/../includes/header.php';
?>

<h2 class="mt-30">Edit Branch: <?php echo htmlspecialchars($branch['branch_name']); ?></h2>

<?php if (!empty($message)): ?>
    <?php echo $message; ?>
<?php endif; ?>

<form action="admin_edit_branch.php?id=<?php echo $branch_id; ?>" method="POST">
    <div class="form-group">
        <label for="branch_name">Branch Name:</label>
        <input type="text" id="branch_name" name="branch_name" required value="<?php echo htmlspecialchars($branch['branch_name']); ?>">
    </div>
    <div class="form-group">
        <label for="location">Location:</label>
        <textarea id="location" name="location" rows="3" required><?php echo htmlspecialchars($branch['location']); ?></textarea>
    </div>
    <div class="form-group">
        <label for="contact_person">Contact Person:</label>
        <input type="text" id="contact_person" name="contact_person" required value="<?php echo htmlspecialchars($branch['contact_person']); ?>">
    </div>
    <div class="form-group">
        <label for="contact_email">Contact Email:</label>
        <input type="email" id="contact_email" name="contact_email" required value="<?php echo htmlspecialchars($branch['contact_email']); ?>">
    </div>
    <div class="form-group">
        <label for="contact_phone">Contact Phone:</label>
        <input type="text" id="contact_phone" name="contact_phone" required value="<?php echo htmlspecialchars($branch['contact_phone']); ?>">
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary"><i class="fas fa-sync-alt"></i> Update Branch</button>
        <a href="admin_manage_branches.php" class="btn btn-secondary">Cancel</a>
    </div>
</form>

<?php
include __DIR__ . '/../includes/footer.php';
$conn->close();
?>