<?php
include 'branch_connection.php';
session_start();
$userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 'Not set';
$message = "";
$edit_mode = false;
$edit_id = 0;

// Handle delete request
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);
    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        $message = "User  deleted successfully.";
    } else {
        $message = "Error deleting user: " . $stmt->error;
    }
    $stmt->close();
}

// Handle form submission for create or update
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = strtoupper(trim($_POST['name']));
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $repassword = trim($_POST['repassword']);
    $status = intval($_POST['segment']);
    $email    = trim($_POST['email']);
$phone    = trim($_POST['phone']);
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;

    // Password validation
    if ($password !== $repassword) {
        $message = "Passwords do not match.";
    } else {
        if ($id > 0) {
            // Update existing user
            $stmt = $conn->prepare("UPDATE users 
SET name=?, username=?, email=?, phone=?, password=?, status=? 
WHERE id=?
");
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt->bind_param(
    "ssssssi",
    $name,
    $username,
    $email,
    $phone,
    $hashed_password,
    $status,
    $id
);

            if ($stmt->execute()) {
                $message = "User  updated successfully.";
            } else {
                $message = "Error updating user: " . $stmt->error;
            }
            $stmt->close();
        } else {
            // Insert new user
            $stmt = $conn->prepare("INSERT INTO users (name, username, email, phone, password, status)
VALUES (?, ?, ?, ?, ?, ?)
");
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
           $stmt->bind_param(
    "sssssi",
    $name,
    $username,
    $email,
    $phone,
    $hashed_password,
    $status
);

            if ($stmt->execute()) {
                $message = "New user created successfully.";
            } else {
                $message = "Error creating user: " . $stmt->error;
            }
            $stmt->close();
        }
    }
}

// If editing, fetch data to populate form
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows == 1) {
        $edit_mode = true;
        $edit_row = $result->fetch_assoc();
    }
    $stmt->close();
}

// Fetch all users for display
$users = [];
$sql = "SELECT * FROM users ORDER BY id DESC";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Positives Programers International</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="author" content="DexignLab">
    <meta name="robots" content="index, follow">
    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/png" href="assets/images/favicon.png">
    <link href="assets/vendor/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-datepicker-master/css/bootstrap-datepicker.min.css" rel="stylesheet">
    <link href="assets/vendor/owl-carousel/owl.carousel.css" rel="stylesheet">
    <link href="assets/css/jquery.localizationTool.css" rel="stylesheet">
    <link class="main-css" href="assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div id="preloader">
        <div class="lds-ripple">
            <div></div>
            <div></div>
        </div>
    </div>
    <div id="main-wrapper">
        <div class="nav-header">
            <a href="index.html" class="brand-logo"><img src="assets/images/logo-02.svg" alt=""></a>
            <div class="nav-control">
                <div class="hamburger"><span class="line"></span><span class="line"></span><span class="line"></span></div>
            </div>
        </div>
        <div class="header">
            <div class="header-content">
                <nav class="navbar navbar-expand">
                    <div class="collapse navbar-collapse justify-content-between">
                        <div class="header-left">
                            <div class="dashboard_bar">Create User</div>
                        </div>
                        <ul class="navbar-nav header-right">
                            <li class="nav-item dropdown notification_dropdown">
                                <a class="nav-link bell dlab-theme-mode p-0" href="javascript:void(0);">
                                    <i id="icon-light" class="fas fa-sun"></i>
                                    <i id="icon-dark" class="fas fa-moon"></i>
                                </a>
                            </li>
                            <?php include "logout.php"; ?>
                        </ul>
                    </div>
                </nav>
            </div>
        </div>
        <?php include "header.php"; ?>
        <div class="content-body">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body" style="padding: 18px;">
                                <div class="basic-form">
                                    <form method="POST" action="">
                                        <input type="hidden" name="id" value="<?php echo $edit_mode ? $edit_row['id'] : ''; ?>">
                                        <div class="row">
                                            <div class="mb-2 col-md-12">
                                                <input type="text" name="name" class="form-control" placeholder="Staff Name" required value="<?php echo $edit_mode ? htmlspecialchars($edit_row['name']) : ''; ?>">
                                            </div>
                                            <div class="mb-2 col-md-12">
                                                <input type="text" name="username" class="form-control" placeholder="User  Name" required value="<?php echo $edit_mode ? htmlspecialchars($edit_row['username']) : ''; ?>">
                                            </div>
                                            <div class="mb-2 col-md-12">
    <input type="email" name="email" class="form-control"
        placeholder="Email Address" required
        value="<?php echo $edit_mode ? htmlspecialchars($edit_row['email']) : ''; ?>">
</div>

<div class="mb-2 col-md-12">
    <input type="text" name="phone" class="form-control"
        placeholder="Phone Number" required
        value="<?php echo $edit_mode ? htmlspecialchars($edit_row['phone']) : ''; ?>">
</div>

                                            <div class="mb-2 col-md-12">
                                                <input type="password" name="password" class="form-control" placeholder="Password" <?php echo $edit_mode ? '' : 'required'; ?>>
                                            </div>
                                            <div class="mb-2 col-md-12">
                                                <input type="password" name="repassword" class="form-control" placeholder="Re Password" <?php echo $edit_mode ? '' : 'required'; ?>>
                                            </div>
                                            <div class="mb-2 col-md-12">
                                                <div class="dropdown bootstrap-select default-select form-control wide dropup">
                                                    <select id="inputState" name="segment" class="default-select form-control wide" required>
                                                        <option value="" disabled selected>Status</option>
                                                        <option value="1" <?php echo $edit_mode && $edit_row['status'] == 1 ? 'selected' : ''; ?>>Enable</option>
                                                        <option value="0" <?php echo $edit_mode && $edit_row['status'] == 0 ? 'selected' : ''; ?>>Disable</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary w-100">Submit</button>
                                    </form>
                                    <?php if ($message): ?>
                                        <div class="alert alert-info mt-3"><?php echo $message; ?></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-8">
                        <div class="row">
                            <div class="table-responsive">
                                <table class="table table-hover table-responsive-sm table-small">
                                    <thead>
                                        <tr>
                                            <th class="td-padding-no">#</th>
                                            <th class="td-padding-no">Staffs</th>
                                            <th class="td-padding-no">Username</th>
<th class="td-padding-no">Email</th>
<th class="td-padding-no">Phone</th>

                                            <th class="td-padding-no">Status</th>
                                            <th class="td-padding-no" style="text-align: left!important;">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($users as $user): ?>
                                            <tr>
                                                <th class="td-padding-no"><?php echo $user['id']; ?></th>
                                                <td class="td-padding-no"><?php echo htmlspecialchars($user['name']); ?></td>
                                                <td class="td-padding-no"><?php echo htmlspecialchars($user['username']); ?></td>
                                                <td><?php echo htmlspecialchars($user['email']); ?></td>
<td><?php echo htmlspecialchars($user['phone']); ?></td>

                                                <td class="td-padding-no"><?php echo $user['status'] == 1 ? 'Enabled' : 'Disabled'; ?></td>
                                                <td class="td-padding-no" style="text-align:center;">
                                                    <span style="gap:2px;width: 100%;text-align:center;" class="d-flex">
                                                        <a href="?edit=<?php echo $user['id']; ?>" title="Edit"><i class="fa fa-edit text-warning mx-1"></i></a>
                                                        <a href="?delete=<?php echo $user['id']; ?>" title="Delete" onclick="return confirm('Are you sure you want to delete this record?');"><i class="fa fa-trash text-danger mx-1"></i></a>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <!-- Pagination can be added here if needed -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include "footer.php"; ?>
    </div>
    <script src="assets/vendor/global/global.min.js"></script>
    <script src="assets/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
    <script src="assets/vendor/bootstrap-datepicker-master/js/bootstrap-datepicker.min.js"></script>
    <script src="assets/vendor/apexchart/apexchart.js"></script>
    <script src="assets/vendor/chartjs/chart.bundle.min.js"></script>
    <script src="assets/vendor/peity/jquery.peity.min.js"></script>
    <script src="assets/js/dashboard/dashboard-1.js"></script>
    <script src="assets/vendor/owl-carousel/owl.carousel.js"></script>
    <script src="assets/js/jquery.localizationTool.js"></script>
    <script src="assets/js/translator.js"></script>    
    <script src="assets/js/custom.min.js"></script>
    <script src="assets/js/dlabnav-init.js"></script>
    <script src="assets/js/demo.js"></script>
</body>
</html>
