<?php
include('includes/header.php');

$table_name = "user";
$msg = "";

// 1. Fetch current admin data (ID 1)
$res = $db->select($table_name, '*', 'id = :id', '', [':id' => 1]);
$row = !empty($res) ? $res[0] : null;

// 2. Handle the Update Form Submission
if (isset($_POST['update_creds'])) {
    $new_user = sanitize($_POST['new_username']);
    $new_pass = sanitize($_POST['new_password']);

    if (!empty($new_user) && !empty($new_pass)) {
        $data = [
            'username' => $new_user,
            'password' => $new_pass
        ];
        
        // Update the admin record
        $db->update($table_name, $data, "id='1'");
        
        // Update session so you aren't kicked out by the header check
        $_SESSION['name'] = $new_user;
        
        $msg = '<div class="alert alert-success">Credentials updated successfully!</div>';
        
        // Refresh to show new data
        echo "<script>setTimeout(function(){ window.location.href='user.php'; }, 2000);</script>";
    } else {
        $msg = '<div class="alert alert-danger">All fields are required.</div>';
    }
}
?>

<div class="col-md-6 mx-auto mt-5">
    <div class="card bg-primary text-white">
        <div class="card-header text-center">
            <h2><i class="fa fa-lock"></i> Update Admin Credentials</h2>
        </div>
        <div class="card-body">
            <?php echo $msg; ?>
            <form method="post">
                <div class="form-group">
                    <label>Current Username</label>
                    <input type="text" class="form-control" value="<?= htmlspecialchars($row['username']) ?>" disabled>
                    <small class="text-light">Current username stored in database.</small>
                </div>
                
                <hr style="border-top: 1px solid rgba(255,255,255,0.2)">
                
                <div class="form-group">
                    <label>New Username</label>
                    <input type="text" name="new_username" class="form-control" placeholder="Enter new username" required>
                </div>
                
                <div class="form-group">
                    <label>New Password</label>
                    <input type="password" name="new_password" class="form-control" placeholder="Enter new password" required>
                </div>
                
                <div class="text-center">
                    <button type="submit" name="update_creds" class="btn btn-warning btn-block">
                        <i class="fa fa-save"></i> Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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