<?php
session_start();
include 'config/database.php';

$page_title = "Staff Registration";

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $database = new Database();
    $db = $database->getConnection();
    
    // Form data collect karna
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = $_POST['role'];
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $salary = $_POST['salary'];
    $join_date = $_POST['join_date'];
    
    // Check if email already exists
    $check_query = "SELECT id FROM staff WHERE email = :email";
    $stmt = $db->prepare($check_query);
    $stmt->bindParam(':email', $email);
    $stmt->execute();
    
    if($stmt->rowCount() > 0) {
        $error = "Email already exists!";
    } else {
        // Insert new staff member
        $query = "INSERT INTO staff (name, email, password, role, phone, address, salary, join_date) 
                  VALUES (:name, :email, :password, :role, :phone, :address, :salary, :join_date)";
        $stmt = $db->prepare($query);
        
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':password', $password);
        $stmt->bindParam(':role', $role);
        $stmt->bindParam(':phone', $phone);
        $stmt->bindParam(':address', $address);
        $stmt->bindParam(':salary', $salary);
        $stmt->bindParam(':join_date', $join_date);
        
        if($stmt->execute()) {
            $_SESSION['success'] = "Staff registration successful! Please login.";
            header("Location: login.php");
            exit();
        } else {
            $error = "Something went wrong! Please try again.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Gym Management - Staff Registration</title>
    <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="assets/vendors/ti-icons/css/themify-icons.css">
    <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
    <link rel="stylesheet" href="assets/vendors/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="shortcut icon" href="assets/images/favicon.png" />
  </head>
  <body>
    <div class="container-scroller">
      <div class="container-fluid page-body-wrapper full-page-wrapper">
        <div class="content-wrapper d-flex align-items-center auth">
          <div class="row flex-grow">
            <div class="col-lg-6 mx-auto">
              <div class="auth-form-light text-left p-5">
                <div class="brand-logo text-center">
                  <img src="assets/images/logo.svg" alt="Gym Logo">
                  <h4 class="mt-3">Gym Management System</h4>
                </div>
                <h4>Staff Registration</h4>
                <h6 class="fw-light">Complete the form to register new staff member</h6>
                
                <!-- Error/Success Messages -->
                <?php if(isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                  <?php echo $error; ?>
                  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <?php if(isset($_SESSION['success'])): ?>
                <div class="alert alert-success alert-dismissible fade show">
                  <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <form class="pt-3" method="POST" action="">
                  <!-- Personal Information -->
                  <div class="row">
                    <div class="col-md-6">
                      <div class="form-group">
                        <label for="name" class="form-label">Full Name *</label>
                        <input type="text" class="form-control form-control-lg" id="name" name="name" 
                               placeholder="Enter full name" required value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
                      </div>
                    </div>
                    <div class="col-md-6">
                      <div class="form-group">
                        <label for="email" class="form-label">Email Address *</label>
                        <input type="email" class="form-control form-control-lg" id="email" name="email" 
                               placeholder="Enter email" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
                      </div>
                    </div>
                  </div>

                  <div class="row">
                    <div class="col-md-6">
                      <div class="form-group">
                        <label for="phone" class="form-label">Phone Number</label>
                        <input type="text" class="form-control form-control-lg" id="phone" name="phone" 
                               placeholder="0300-1234567" value="<?php echo isset($_POST['phone']) ? $_POST['phone'] : ''; ?>">
                      </div>
                    </div>
                    <div class="col-md-6">
                      <div class="form-group">
                        <label for="role" class="form-label">Staff Role *</label>
                        <select class="form-control form-control-lg" id="role" name="role" required>
                          <option value="">Select Role</option>
                          <option value="super_admin" <?php echo (isset($_POST['role']) && $_POST['role'] == 'super_admin') ? 'selected' : ''; ?>>Super Admin</option>
                          <option value="gym_manager" <?php echo (isset($_POST['role']) && $_POST['role'] == 'gym_manager') ? 'selected' : ''; ?>>Gym Manager</option>
                          <option value="trainer" <?php echo (isset($_POST['role']) && $_POST['role'] == 'trainer') ? 'selected' : ''; ?>>Trainer</option>
                          <option value="receptionist" <?php echo (isset($_POST['role']) && $_POST['role'] == 'receptionist') ? 'selected' : ''; ?>>Receptionist</option>
                        </select>
                      </div>
                    </div>
                  </div>

                  <div class="row">
                    <div class="col-md-6">
                      <div class="form-group">
                        <label for="salary" class="form-label">Salary (PKR)</label>
                        <input type="number" class="form-control form-control-lg" id="salary" name="salary" 
                               placeholder="50000" step="0.01" value="<?php echo isset($_POST['salary']) ? $_POST['salary'] : ''; ?>">
                      </div>
                    </div>
                    <div class="col-md-6">
                      <div class="form-group">
                        <label for="join_date" class="form-label">Join Date</label>
                        <input type="date" class="form-control form-control-lg" id="join_date" name="join_date" 
                               value="<?php echo isset($_POST['join_date']) ? $_POST['join_date'] : date('Y-m-d'); ?>">
                      </div>
                    </div>
                  </div>

                  <div class="form-group">
                    <label for="address" class="form-label">Address</label>
                    <textarea class="form-control form-control-lg" id="address" name="address" 
                              placeholder="Enter full address" rows="2"><?php echo isset($_POST['address']) ? $_POST['address'] : ''; ?></textarea>
                  </div>

                  <div class="form-group">
                    <label for="password" class="form-label">Password *</label>
                    <input type="password" class="form-control form-control-lg" id="password" name="password" 
                           placeholder="Enter password" required>
                  </div>

                  <div class="form-group">
                    <label for="confirm_password" class="form-label">Confirm Password *</label>
                    <input type="password" class="form-control form-control-lg" id="confirm_password" name="confirm_password" 
                           placeholder="Confirm password" required>
                  </div>


                  <div class="mt-3 d-grid gap-2">
                    <button type="submit" class="btn btn-block btn-primary btn-lg fw-semibold auth-form-btn">
                      <i class="mdi mdi-account-plus me-2"></i>REGISTER STAFF
                    </button>
                  </div>

                  <div class="text-center mt-4 fw-light"> 
                    Already have an account? <a href="login.php" class="text-primary">Login</a>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <script src="assets/vendors/js/vendor.bundle.base.js"></script>
    <script>
      // Password confirmation check
      document.querySelector('form').addEventListener('submit', function(e) {
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirm_password').value;
        
        if (password !== confirmPassword) {
          e.preventDefault();
          alert('Passwords do not match!');
          return false;
        }
        
        if (password.length < 6) {
          e.preventDefault();
          alert('Password must be at least 6 characters long!');
          return false;
        }
      });

      // Phone number formatting
      document.getElementById('phone').addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        if (value.length <= 11) {
          if (value.length >= 4) {
            value = value.replace(/(\d{4})(\d{0,7})/, '$1-$2');
          }
          e.target.value = value;
        } else {
          e.target.value = value.slice(0, 12);
        }
      });
    </script>
  </body>
</html>