<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid']) || $_SESSION['usertype'] != 'admin') {
    header('location:logout.php');
    exit();
}

$msg = "";

// CREATE
if(isset($_POST['create'])) {
    $username = mysqli_real_escape_string($con, $_POST['username']);
    $fullname = mysqli_real_escape_string($con, $_POST['fullname']);
    $usertype = mysqli_real_escape_string($con, $_POST['usertype']);
    $mobilenumber = mysqli_real_escape_string($con, $_POST['mobilenumber']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $password = md5($_POST['password']);

    $check = mysqli_query($con, "SELECT ID FROM tblusers WHERE UserName='$username'");
    if(mysqli_num_rows($check) > 0) {
        $msg = "Username already exists!";
    } else {
        $result = mysqli_query($con, "INSERT INTO tblusers (UserName, FullName, UserType, MobileNumber, Email, Password) VALUES ('$username', '$fullname', '$usertype', '$mobilenumber', '$email', '$password')");
        $msg = $result ? "User created successfully!" : "Error creating user!";
    }
}

// UPDATE
if(isset($_POST['update'])) {
    $userid = intval($_POST['userid']);
    $fullname = mysqli_real_escape_string($con, $_POST['fullname']);
    $usertype = mysqli_real_escape_string($con, $_POST['usertype']);
    $mobilenumber = mysqli_real_escape_string($con, $_POST['mobilenumber']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $updateQuery = "UPDATE tblusers SET FullName='$fullname', UserType='$usertype', MobileNumber='$mobilenumber', Email='$email'";
    if(!empty($_POST['password'])) {
        $password = md5($_POST['password']);
        $updateQuery .= ", Password='$password'";
    }
    $updateQuery .= " WHERE ID='$userid'";
    $result = mysqli_query($con, $updateQuery);
    $msg = $result ? "User updated successfully!" : "Error updating user!";
}

// DELETE
if(isset($_GET['del'])) {
    $userid = intval($_GET['del']);
    if($userid != $_SESSION['uid']) { // Prevent self-delete
        mysqli_query($con, "DELETE FROM tblusers WHERE ID='$userid'");
        $msg = "User deleted successfully!";
    } else {
        $msg = "You cannot delete your own account!";
    }
}

// READ (fetch all users)
$users = mysqli_query($con, "SELECT * FROM tblusers ORDER BY ID DESC");

// For edit form
$editUser = null;
if(isset($_GET['edit'])) {
    $editid = intval($_GET['edit']);
    $editRes = mysqli_query($con, "SELECT * FROM tblusers WHERE ID='$editid'");
    $editUser = mysqli_fetch_assoc($editRes);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Mariyappa Nadar Ricemill | User Management</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <style>
        body { background: #f8fafc; }
        .card { border-radius: 1rem; }
        .card-header { border-radius: 1rem 1rem 0 0; }
        .form-control, .btn { font-size: 1.1rem; border-radius: 2rem; }
        .btn-block { padding: 0.75rem 0; }
        .table th, .table td { vertical-align: middle !important; }
        @media (max-width: 767.98px) {
            .container, .container-fluid { padding-left: 0.5rem; padding-right: 0.5rem; }
            .card { margin-bottom: 1.2rem; }
            .table-responsive { font-size: 0.95rem; }
            .btn, .btn-block { font-size: 1rem; padding: 0.6rem 0.75rem; }
            .card-header h4, .card-header h5 { font-size: 1.1rem; }
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                <div class="container-fluid mt-3 mb-3">
                  
                    <div class="row justify-content-center">
                        <div class="col-lg-7 col-md-10 col-12">
                            <div class="card shadow mb-4">
                                <div class="card-header bg-primary text-white text-center">
                                    <h4 class="mb-0"><?php echo $editUser ? "Edit User" : "Create New User"; ?></h4>
                                </div>
                                <div class="card-body">
                                    <?php if($msg) { ?>
                                        <div class="alert alert-info text-center"><?php echo $msg; ?></div>
                                    <?php } ?>
                                    <form method="post" autocomplete="off">
                                        <?php if($editUser) { ?>
                                            <input type="hidden" name="userid" value="<?php echo $editUser['ID']; ?>">
                                        <?php } ?>
                                        <div class="form-group">
                                            <label>Full Name</label>
                                            <input type="text" name="fullname" class="form-control" required value="<?php echo $editUser ? htmlspecialchars($editUser['FullName']) : ''; ?>">
                                        </div>
                                        <?php if(!$editUser) { ?>
                                        <div class="form-group">
                                            <label>User Name</label>
                                            <input type="text" name="username" class="form-control" required>
                                        </div>
                                        <?php } else { ?>
                                        <div class="form-group">
                                            <label>User Name</label>
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($editUser['UserName']); ?>" readonly>
                                        </div>
                                        <?php } ?>
                                        <div class="form-group">
                                            <label>User Type</label>
                                            <select name="usertype" class="form-control" required>
                                                <option value="admin" <?php if($editUser && $editUser['UserType']=='admin') echo 'selected'; ?>>Admin</option>
                                                <option value="staff" <?php if($editUser && $editUser['UserType']=='staff') echo 'selected'; ?>>Staff</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Mobile Number</label>
                                            <input type="text" name="mobilenumber" class="form-control" maxlength="15" value="<?php echo $editUser ? htmlspecialchars($editUser['MobileNumber']) : ''; ?>">
                                        </div>
                                        <div class="form-group">
                                            <label>Email</label>
                                            <input type="email" name="email" class="form-control" value="<?php echo $editUser ? htmlspecialchars($editUser['Email']) : ''; ?>">
                                        </div>
                                        <div class="form-group">
                                            <label><?php echo $editUser ? "New Password (leave blank to keep current)" : "Password"; ?></label>
                                            <input type="password" name="password" class="form-control" <?php echo $editUser ? "" : "required"; ?>>
                                        </div>
                                        <input type="submit" name="<?php echo $editUser ? "update" : "create"; ?>" class="btn btn-primary btn-user btn-block" value="<?php echo $editUser ? "Update User" : "Create User"; ?>">
                                        <?php if($editUser) { ?>
                                            <a href="create-user.php" class="btn btn-secondary btn-block mt-2">Cancel Edit</a>
                                        <?php } ?>
                                    </form>
                                </div>
                            </div>
                            <div class="card shadow">
                                <div class="card-header bg-info text-white text-center">
                                    <h5 class="mb-0">All Users</h5>
                                </div>
                                <div class="card-body p-2">
                                    <div class="table-responsive">
                                    <table class="table table-bordered table-sm mb-0">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>#</th>
                                                <th>User Name</th>
                                                <th>Full Name</th>
                                                <th>User Type</th>
                                                <th>Mobile</th>
                                                <th>Email</th>
                                                <th style="min-width:90px;">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        <?php $i=1; while($row = mysqli_fetch_assoc($users)) { ?>
                                            <tr>
                                                <td><?php echo $i++; ?></td>
                                                <td><?php echo htmlspecialchars($row['UserName']); ?></td>
                                                <td><?php echo htmlspecialchars($row['FullName']); ?></td>
                                                <td><?php echo ucfirst($row['UserType']); ?></td>
                                                <td><?php echo htmlspecialchars($row['MobileNumber']); ?></td>
                                                <td><?php echo htmlspecialchars($row['Email']); ?></td>
                                                <td>
                                                    <div class="d-flex flex-wrap gap-1">
                                                        <a href="create-user.php?edit=<?php echo $row['ID']; ?>" class="btn btn-sm btn-warning mb-1">Edit</a>
                                                        <?php if($row['ID'] != $_SESSION['uid']) { ?>
                                                        <a href="create-user.php?del=<?php echo $row['ID']; ?>" class="btn btn-sm btn-danger mb-1" onclick="return confirm('Delete this user?');">Delete</a>
                                                        <?php } ?>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php } ?>
                                        </tbody>
                                    </table>
                                    </div>
                                </div>
                            </div>
                            <a href="dashboard.php" class="btn btn-link btn-block mt-3">Back to Dashboard</a>
                        </div>
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>
            <!-- End of Main Content -->
            <?php include_once('includes/footer.php');?>
        </div>
        <!-- End of Content Wrapper -->
    </div>
    <!-- End of Page Wrapper -->
    <?php include_once('includes/footer2.php');?>
    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- Core plugin JavaScript-->
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <!-- Custom scripts for all pages-->
    <script src="js/sb-admin-2.min.js"></script>
</body>
</html>
