<?php
// Check if user is logged in and is an admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
   
header("Location: index.php?page=login");
   exit();
}

// Initialize variables
$error_message "";
$success_message "";
$person_id 0;
$username "";
$email "";
$firstName "";
$lastName "";
$isAdmin 0;
$isActive 1;
$show_form false// Default to hiding the form

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
// Create or Update person
    
if (isset($_POST['save_person'])) {
        
$person_id = isset($_POST['person_id']) ? intval($_POST['person_id']) : 0;
        
$username mysqli_real_escape_string($dbctrim($_POST['username']));
        
$email mysqli_real_escape_string($dbctrim($_POST['email']));
        
$firstName mysqli_real_escape_string($dbctrim($_POST['firstName']));
        
$lastName mysqli_real_escape_string($dbctrim($_POST['lastName']));
        
$isAdmin = isset($_POST['isAdmin']) ? 0;
        
$isActive = isset($_POST['isActive']) ? 0;
        
        
// Validate required fields
        
if (empty($username) || empty($email) || empty($firstName) || empty($lastName)) {
            
$error_message "Username, email, first name, and last name are required fields.";
            
$show_form true// Show form if there are errors
        
} else {
            
// Check if username or email already exists (for new users)
            
if ($person_id === 0) {
                
$check_query "SELECT pk_Person FROM CINE_Person WHERE username = ? OR email = ?";
                
$check_stmt mysqli_prepare($dbc$check_query);
                
mysqli_stmt_bind_param($check_stmt"ss"$username$email);
                
mysqli_stmt_execute($check_stmt);
                
$check_result mysqli_stmt_get_result($check_stmt);
                
                if (
mysqli_num_rows($check_result) > 0) {
                    
$error_message "Username or email already exists.";
                    
$show_form true// Show form if there are errors
                
}
                
mysqli_stmt_close($check_stmt);
            }
            
            
// If no errors, proceed with insert/update
            
if (empty($error_message)) {
                
// Handle password
                
$password_part "";
                
$password_param "";
                
                
// If it's a new user or password is being changed
                
if (($person_id === || !empty($_POST['password'])) && isset($_POST['password'])) {
                    
$password trim($_POST['password']);
                    if (
strlen($password) < 6) {
                        
$error_message "Password must be at least 6 characters long.";
                        
$show_form true// Show form if there are errors
                    
} else {
                        
$hashed_password password_hash($passwordPASSWORD_DEFAULT);
                        
$password_part ", password = ?";
                        
$password_param "s";
                    }
                }
                
                if (empty(
$error_message)) {
                    if (
$person_id === 0) {
                        
// Insert new person
                        
$query "INSERT INTO CINE_Person (username, email, firstName, lastName, password, isAdmin, isActive) 
                                VALUES (?, ?, ?, ?, ?, ?, ?)"
;
                        
$stmt mysqli_prepare($dbc$query);
                        
mysqli_stmt_bind_param($stmt"sssssii"$username$email$firstName$lastName$hashed_password$isAdmin$isActive);
                    } else {
                        
// Update existing person
                        
if (!empty($password_part)) {
                            
$query "UPDATE CINE_Person SET username = ?, email = ?, firstName = ?, lastName = ?{$password_part}, isAdmin = ?, isActive = ? WHERE pk_Person = ?";
                            
$stmt mysqli_prepare($dbc$query);
                            
mysqli_stmt_bind_param($stmt"ssss{$password_param}iii"$username$email$firstName$lastName$hashed_password$isAdmin$isActive$person_id);
                        } else {
                            
$query "UPDATE CINE_Person SET username = ?, email = ?, firstName = ?, lastName = ?, isAdmin = ?, isActive = ? WHERE pk_Person = ?";
                            
$stmt mysqli_prepare($dbc$query);
                            
mysqli_stmt_bind_param($stmt"ssssiii"$username$email$firstName$lastName$isAdmin$isActive$person_id);
                        }
                    }
                    
                    if (
mysqli_stmt_execute($stmt)) {
                        
$success_message = ($person_id === 0) ? "Person added successfully." "Person updated successfully.";
                        
// Reset form fields for new entry
                        
if ($person_id === 0) {
                            
$username $email $firstName $lastName "";
                            
$isAdmin 0;
                            
$isActive 1;
                            
$show_form false// Hide form after successful add
                        
}
                    } else {
                        
$error_message "Error: " mysqli_stmt_error($stmt);
                        
$show_form true// Show form if there are errors
                    
}
                    
mysqli_stmt_close($stmt);
                }
            }
        }
    }
    
    
// Delete person
    
if (isset($_POST['delete_person'])) {
        
$person_id intval($_POST['person_id']);
        
        
// Check if person exists
        
$check_query "SELECT pk_Person FROM CINE_Person WHERE pk_Person = ?";
        
$check_stmt mysqli_prepare($dbc$check_query);
        
mysqli_stmt_bind_param($check_stmt"i"$person_id);
        
mysqli_stmt_execute($check_stmt);
        
$check_result mysqli_stmt_get_result($check_stmt);
        
        if (
mysqli_num_rows($check_result) > 0) {
            
// Delete the person
            
$delete_query "DELETE FROM CINE_Person WHERE pk_Person = ?";
            
$delete_stmt mysqli_prepare($dbc$delete_query);
            
mysqli_stmt_bind_param($delete_stmt"i"$person_id);
            
            if (
mysqli_stmt_execute($delete_stmt)) {
                
$success_message "Person deleted successfully.";
            } else {
                
$error_message "Error deleting person: " mysqli_stmt_error($delete_stmt);
            }
            
mysqli_stmt_close($delete_stmt);
        } else {
            
$error_message "Person not found.";
        }
        
mysqli_stmt_close($check_stmt);
    }
    
    
// Edit person (load data for editing)
    
if (isset($_POST['edit_person'])) {
        
$person_id intval($_POST['person_id']);
        
$show_form true// Show form when editing
        
        
$query "SELECT * FROM CINE_Person WHERE pk_Person = ?";
        
$stmt mysqli_prepare($dbc$query);
        
mysqli_stmt_bind_param($stmt"i"$person_id);
        
mysqli_stmt_execute($stmt);
        
$result mysqli_stmt_get_result($stmt);
        
        if (
$row mysqli_fetch_assoc($result)) {
            
$username $row['username'];
            
$email $row['email'];
            
$firstName $row['firstName'];
            
$lastName $row['lastName'];
            
$isAdmin $row['isAdmin'];
            
$isActive $row['isActive'];
        } else {
            
$error_message "Person not found.";
        }
        
mysqli_stmt_close($stmt);
    }
    
    
// Show add form
    
if (isset($_POST['show_add_form'])) {
        
$show_form true;
        
$person_id 0// Reset person ID for new entry
        
$username $email $firstName $lastName "";
        
$isAdmin 0;
        
$isActive 1;
    }
}

// Get all persons for display
$persons = [];
$query "SELECT * FROM CINE_Person ORDER BY username";
$result mysqli_query($dbc$query);

if (
$result) {
    while (
$row mysqli_fetch_assoc($result)) {
        
$persons[] = $row;
    }
    
mysqli_free_result($result);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Persons - Ciné Le Paris</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link rel="stylesheet" href="assets/css/persons.css">
</head>
<body>
    <div class="persons-container">
        <!-- Header -->
        <div class="persons-header">
            <div class="persons-title-section">
                <h1 class="persons-title">Manage Users</h1>
                <p class="persons-subtitle">Add, edit, and manage user accounts</p>
            </div>
        </div>
        
        <?php if (!empty($error_message)): ?>
            <div class="error-message">
                <div class="plans-alert-icon">
                    <span class="material-symbols-outlined">error</span>
                </div>
                <div class="plans-alert-content">
                    <?php echo $error_message?>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($success_message)): ?>
            <div class="success-message">
                <div class="plans-alert-icon">
                    <span class="material-symbols-outlined">check_circle</span>
                </div>
                <div class="plans-alert-content">
                    <?php echo $success_message?>
                </div>
            </div>
        <?php endif; ?>
        
        <!-- Form Container -->
        <div class="persons-form-container <?php echo $show_form 'show' ''?>" id="personsForm">
            <div class="form-header">
                <h2><?php echo ($person_id 0) ? 'Edit User' 'Add New User'?></h2>
                <button type="button" class="btn-close" id="closeFormBtn" title="Close Form">×</button>
            </div>
            
            <form method="POST" action="index.php?page=persons" class="persons-form">
                <input type="hidden" name="person_id" value="<?php echo $person_id?>">
                
                <div class="form-group">
                    <label for="username">Username <span class="required">*</span></label>
                    <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($username); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="email">Email <span class="required">*</span></label>
                    <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="password"><?php echo ($person_id 0) ? 'Password (leave blank to keep current)' 'Password <span class="required">*</span>'?></label>
                    <input type="password" id="password" name="password" <?php echo ($person_id === 0) ? 'required' ''?>>
                    <?php if ($person_id 0): ?>
                        <small>Leave blank to keep current password</small>
                    <?php endif; ?>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="firstName">First Name <span class="required">*</span></label>
                        <input type="text" id="firstName" name="firstName" value="<?php echo htmlspecialchars($firstName); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="lastName">Last Name <span class="required">*</span></label>
                        <input type="text" id="lastName" name="lastName" value="<?php echo htmlspecialchars($lastName); ?>" required>
                    </div>
                </div>
                
                <div class="checkbox-row">
                    <div class="checkbox-group">
                        <input type="checkbox" id="isAdmin" name="isAdmin" <?php echo ($isAdmin == 1) ? 'checked' ''?>>
                        <label for="isAdmin">Administrator</label>
                    </div>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" id="isActive" name="isActive" <?php echo ($isActive == 1) ? 'checked' ''?>>
                        <label for="isActive">Active</label>
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" name="save_person" class="btn-save">
                        <span class="material-symbols-outlined">save</span>
                        <?php echo ($person_id 0) ? 'Update User' 'Add User'?>
                    </button>
                    
                    <?php if ($person_id 0): ?>
                        <a href="index.php?page=persons" class="btn-cancel">
                            <span class="material-symbols-outlined">cancel</span> Cancel
                        </a>
                    <?php endif; ?>
                </div>
            </form>
        </div>
        
        <!-- Persons List -->
        <div class="persons-list-container">
            <div class="list-header">
                <h2>Users List</h2>
                <form method="POST" action="index.php?page=persons" class="add-person-form">
                    <button type="submit" name="show_add_form" class="btn-add-person" id="showFormBtn">
                        <span class="material-symbols-outlined">add</span> Add User
                    </button>
                </form>
            </div>
            
            <?php if (count($persons) > 0): ?>
                <div class="persons-table-container">
                    <table class="persons-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Username</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Role</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($persons as $person): ?>
                                <tr>
                                    <td><?php echo $person['pk_Person']; ?></td>
                                    <td><?php echo htmlspecialchars($person['username']); ?></td>
                                    <td>
                                        <?php echo htmlspecialchars($person['firstName'] . ' ' $person['lastName']); ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($person['email']); ?></td>
                                    <td>
                                        <?php if ($person['isAdmin'] == 1): ?>
                                            <span class="badge admin-badge">
                                                <span class="material-symbols-outlined">admin_panel_settings</span> Admin
                                            </span>
                                        <?php else: ?>
                                            <span class="badge user-badge">
                                                <span class="material-symbols-outlined">person</span> User
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="status-badge <?php echo ($person['isActive'] == 1) ? 'active-badge' 'inactive-badge'?>">
                                            <span class="material-symbols-outlined">
                                                <?php echo ($person['isActive'] == 1) ? 'check_circle' 'cancel'?>
                                            </span>
                                            <?php echo ($person['isActive'] == 1) ? 'Active' 'Inactive'?>
                                        </span>
                                    </td>
                                    <td class="persons-actions-cell">
                                        <div class="action-buttons">
                                            <form method="POST" action="index.php?page=persons" class="edit-form">
                                                <input type="hidden" name="person_id" value="<?php echo $person['pk_Person']; ?>">
                                                <button type="submit" name="edit_person" class="btn-edit" title="Edit User">
                                                    <span class="material-symbols-outlined">edit</span>
                                                </button>
                                            </form>
                                            
                                            <form method="POST" action="index.php?page=persons" class="delete-form" onsubmit="return confirm('Are you sure you want to delete this user?');">
                                                <input type="hidden" name="person_id" value="<?php echo $person['pk_Person']; ?>">
                                                <button type="submit" name="delete_person" class="btn-delete" title="Delete User">
                                                    <span class="material-symbols-outlined">delete</span>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="no-records">
                    <div class="plans-empty-icon">
                        <span class="material-symbols-outlined">person_off</span>
                    </div>
                    <p class="plans-empty-text">No users found.</p>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Back to Dashboard Button -->
        <div class="back-to-dashboard">
            <a href="index.php?page=dashboard" class="btn-back">
                <span class="material-symbols-outlined">dashboard</span> Back to Dashboard
            </a>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Show success message for a limited time
            const successMessage = document.querySelector('.success-message');
            if (successMessage) {
                setTimeout(function() {
                    successMessage.style.opacity = '0';
                    setTimeout(function() {
                        successMessage.style.display = 'none';
                    }, 500);
                }, 3000);
            }
            
            // Form toggle functionality with JavaScript (as a fallback)
            const formContainer = document.getElementById('personsForm');
            const closeFormBtn = document.getElementById('closeFormBtn');
            
            // Close form button
            if (closeFormBtn) {
                closeFormBtn.addEventListener('click', function() {
                    formContainer.classList.remove('show');
                });
            }
        });
    </script>
</body>
</html>