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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

$user_id = $_GET['id'] ?? 0;

// Get user details
$sql = "SELECT u.*, r.role_name,
        CONCAT(u.first_name, ' ', COALESCE(u.middle_name, ''), ' ', u.last_name) as full_name
        FROM users u
        INNER JOIN roles r ON u.role_id = r.id
        WHERE u.id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "User not found!";
    header('Location: list_users.php');
    exit();
}

$user = $result->fetch_assoc();

// Get all roles
$roles_sql = "SELECT * FROM roles ORDER BY role_name";
$roles_result = $conn->query($roles_sql);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = trim($_POST['first_name']);
    $middle_name = trim($_POST['middle_name'] ?? '');
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $phone_secondary = trim($_POST['phone_secondary'] ?? '');
    $role_id = $_POST['role_id'];
    $gender = $_POST['gender'] ?? null;
    $dob = $_POST['dob'] ?? null;
    $nationality = $_POST['nationality'] ?? null;
    $id_type = $_POST['id_type'] ?? 'National ID';
    $id_number = $_POST['id_number'] ?? null;
    $address_postal = $_POST['address_postal'] ?? null;
    $city = $_POST['city'] ?? null;
    $country = $_POST['country'] ?? 'Kenya';
    $status = $_POST['status'];
    
    // Validate email uniqueness
    $email_check_sql = "SELECT id FROM users WHERE email = ? AND id != ?";
    $email_stmt = $conn->prepare($email_check_sql);
    $email_stmt->bind_param("si", $email, $user_id);
    $email_stmt->execute();
    if ($email_stmt->get_result()->num_rows > 0) {
        $_SESSION['error_message'] = "Email already exists!";
    } else {
        // Update user
        $update_sql = "UPDATE users SET 
                      first_name = ?, middle_name = ?, last_name = ?, 
                      email = ?, phone = ?, phone_secondary = ?,
                      role_id = ?, gender = ?, dob = ?, nationality = ?,
                      id_type = ?, id_number = ?, 
                      address_postal = ?, city = ?, country = ?,
                      status = ?, updated_at = NOW()
                      WHERE id = ?";
        
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("ssssssisssssssssi", 
            $first_name, $middle_name, $last_name,
            $email, $phone, $phone_secondary,
            $role_id, $gender, $dob, $nationality,
            $id_type, $id_number,
            $address_postal, $city, $country,
            $status, $user_id
        );
        
        if ($update_stmt->execute()) {
            // Log activity
            $activity_sql = "INSERT INTO activity_logs (user_id, action_type, module, reference_id, new_values) 
                           VALUES (?, 'UPDATE', 'USER', ?, ?)";
            $activity_stmt = $conn->prepare($activity_sql);
            $new_values = json_encode(['user_id' => $user_id, 'updated_by' => $_SESSION['user_id']]);
            $activity_stmt->bind_param("iis", $_SESSION['user_id'], $user_id, $new_values);
            $activity_stmt->execute();
            
            $_SESSION['success_message'] = "User updated successfully!";
            header('Location: view_user.php?id=' . $user_id);
            exit();
        } else {
            $_SESSION['error_message'] = "Failed to update user!";
        }
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit User')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Users', 'title' => 'Edit User')); ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php 
                                echo $_SESSION['error_message']; 
                                unset($_SESSION['error_message']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Edit User Information</h4>
                                </div>
                                <div class="card-body">
                                    <form method="POST" id="editUserForm">
                                        <div class="row">
                                            <!-- Personal Information -->
                                            <div class="col-12">
                                                <h5 class="mb-3">Personal Information</h5>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">First Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="first_name" 
                                                       value="<?php echo htmlspecialchars($user['first_name']); ?>" required>
                                            </div>

                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Middle Name</label>
                                                <input type="text" class="form-control" name="middle_name" 
                                                       value="<?php echo htmlspecialchars($user['middle_name'] ?? ''); ?>">
                                            </div>

                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Last Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="last_name" 
                                                       value="<?php echo htmlspecialchars($user['last_name']); ?>" required>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Gender</label>
                                                <select class="form-select" name="gender">
                                                    <option value="">Select Gender</option>
                                                    <option value="Male" <?php echo ($user['gender'] ?? '') == 'Male' ? 'selected' : ''; ?>>Male</option>
                                                    <option value="Female" <?php echo ($user['gender'] ?? '') == 'Female' ? 'selected' : ''; ?>>Female</option>
                                                    <option value="Other" <?php echo ($user['gender'] ?? '') == 'Other' ? 'selected' : ''; ?>>Other</option>
                                                    <option value="Prefer Not to Say" <?php echo ($user['gender'] ?? '') == 'Prefer Not to Say' ? 'selected' : ''; ?>>Prefer Not to Say</option>
                                                </select>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Date of Birth</label>
                                                <input type="date" class="form-control" name="dob" 
                                                       value="<?php echo $user['dob'] ?? ''; ?>">
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Nationality</label>
                                                <input type="text" class="form-control" name="nationality" 
                                                       value="<?php echo htmlspecialchars($user['nationality'] ?? 'Kenyan'); ?>">
                                            </div>

                                            <!-- Contact Information -->
                                            <div class="col-12 mt-3">
                                                <h5 class="mb-3">Contact Information</h5>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Email <span class="text-danger">*</span></label>
                                                <input type="email" class="form-control" name="email" 
                                                       value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Phone <span class="text-danger">*</span></label>
                                                <input type="tel" class="form-control" name="phone" 
                                                       value="<?php echo htmlspecialchars($user['phone']); ?>" 
                                                       placeholder="+254712345678" required>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Secondary Phone</label>
                                                <input type="tel" class="form-control" name="phone_secondary" 
                                                       value="<?php echo htmlspecialchars($user['phone_secondary'] ?? ''); ?>" 
                                                       placeholder="+254712345678">
                                            </div>

                                            <!-- Address Information -->
                                            <div class="col-12 mt-3">
                                                <h5 class="mb-3">Address Information</h5>
                                            </div>

                                            <div class="col-md-12 mb-3">
                                                <label class="form-label">Postal Address</label>
                                                <input type="text" class="form-control" name="address_postal" 
                                                       value="<?php echo htmlspecialchars($user['address_postal'] ?? ''); ?>"
                                                       placeholder="P.O. Box 12345-00100">
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">City</label>
                                                <input type="text" class="form-control" name="city" 
                                                       value="<?php echo htmlspecialchars($user['city'] ?? ''); ?>">
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Country</label>
                                                <input type="text" class="form-control" name="country" 
                                                       value="<?php echo htmlspecialchars($user['country'] ?? 'Kenya'); ?>">
                                            </div>

                                            <!-- Identification -->
                                            <div class="col-12 mt-3">
                                                <h5 class="mb-3">Identification</h5>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">ID Type</label>
                                                <select class="form-select" name="id_type">
                                                    <option value="National ID" <?php echo ($user['id_type'] ?? 'National ID') == 'National ID' ? 'selected' : ''; ?>>National ID</option>
                                                    <option value="Passport" <?php echo ($user['id_type'] ?? '') == 'Passport' ? 'selected' : ''; ?>>Passport</option>
                                                    <option value="Alien ID" <?php echo ($user['id_type'] ?? '') == 'Alien ID' ? 'selected' : ''; ?>>Alien ID</option>
                                                </select>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">ID Number</label>
                                                <input type="text" class="form-control" name="id_number" 
                                                       value="<?php echo htmlspecialchars($user['id_number'] ?? ''); ?>">
                                            </div>

                                            <!-- System Information -->
                                            <div class="col-12 mt-3">
                                                <h5 class="mb-3">System Access</h5>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Role <span class="text-danger">*</span></label>
                                                <select class="form-select" name="role_id" required>
                                                    <?php while($role = $roles_result->fetch_assoc()): ?>
                                                        <option value="<?php echo $role['id']; ?>" 
                                                                <?php echo $user['role_id'] == $role['id'] ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($role['role_name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Status <span class="text-danger">*</span></label>
                                                <select class="form-select" name="status" required>
                                                    <option value="active" <?php echo ($user['status'] ?? 'active') == 'active' ? 'selected' : ''; ?>>Active</option>
                                                    <option value="inactive" <?php echo ($user['status'] ?? '') == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                                    <option value="pending_verification" <?php echo ($user['status'] ?? '') == 'pending_verification' ? 'selected' : ''; ?>>Pending Verification</option>
                                                    <option value="banned" <?php echo ($user['status'] ?? '') == 'banned' ? 'selected' : ''; ?>>Banned</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="mt-4 border-top pt-3">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line me-1"></i>Update User
                                            </button>
                                            <a href="view_user.php?id=<?php echo $user_id; ?>" class="btn btn-secondary ms-2">
                                                <i class="ri-close-line me-1"></i>Cancel
                                            </a>
                                            <a href="list_users.php" class="btn btn-soft-secondary ms-2">
                                                <i class="ri-arrow-left-line me-1"></i>Back to Users
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Form validation
        document.getElementById('editUserForm').addEventListener('submit', function(e) {
            const phone = document.querySelector('[name="phone"]').value;
            
            // Basic phone validation
            if (phone && !phone.match(/^\+?[0-9]{10,15}$/)) {
                e.preventDefault();
                alert('Please enter a valid phone number');
                return false;
            }
        });
    </script>
</body>
</html>