<?php
session_start();
include('includes/config.php');
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

if (isset($_POST['signup'])) {
  $StaffId = trim($_POST['staffid']);
  $fname = trim($_POST['fullname']);
  $mobileno = trim($_POST['mobileno']);
  $email = trim($_POST['email']);
  $passwordRaw = $_POST['password'];
  $confirmPwd = $_POST['confirmpassword'];
  $address = trim($_POST['address']);
  $qualification = trim($_POST['qualification']);
  $joiningDate = trim($_POST['joiningdate']);
  $status = 2;

  $uploadDirId = "uploads/idproofs/";
  $uploadDirPhoto = "uploads/photos/";

  // Validation
  if ($passwordRaw !== $confirmPwd) {
    $_SESSION['error'] = 'Passwords do not match.';
  } elseif (!preg_match('/[A-Z]/', $passwordRaw) || !preg_match('/[^a-zA-Z0-9]/', $passwordRaw) || strlen($passwordRaw) < 6) {
    $_SESSION['error'] = 'Password must be at least 6 characters, include an uppercase letter and a special character.';
  } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $_SESSION['error'] = 'Invalid email format.';
  } elseif (empty($_POST['gender_id']) || empty($_POST['department_id']) || empty($_POST['designation_id']) || empty($_POST['degree_id'])) {
    $_SESSION['error'] = 'Please select Gender, Department, Designation, and Degree.';
  } else {
    $gender_id = intval($_POST['gender_id']);
    $department_id = intval($_POST['department_id']);
    $designation_id = intval($_POST['designation_id']);
    $degree_id = intval($_POST['degree_id']);

    // Check if StaffId already exists
    $checkStmt = $dbh->prepare("SELECT StaffId FROM tblstaff WHERE StaffId = :sid");
    $checkStmt->bindParam(':sid', $StaffId, PDO::PARAM_STR);
    $checkStmt->execute();

    if ($checkStmt->rowCount() > 0) {
      $_SESSION['error'] = 'This Staff ID is already registered.';
    } else {
      // Create directories if not exist
      if (!file_exists($uploadDirId))
        mkdir($uploadDirId, 0755, true);
      if (!file_exists($uploadDirPhoto))
        mkdir($uploadDirPhoto, 0755, true);

      $idProofPath = '';
      $photoPath = '';

      // Handle ID proof upload
      if (isset($_FILES['idproof']) && $_FILES['idproof']['error'] == 0) {
        $idProofName = time() . "_" . basename($_FILES["idproof"]["name"]);
        $idProofPath = $uploadDirId . $idProofName;
        move_uploaded_file($_FILES["idproof"]["tmp_name"], $idProofPath);
      }

      // Handle photo upload
      if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
        $photoName = time() . "_" . basename($_FILES["photo"]["name"]);
        $photoPath = $uploadDirPhoto . $photoName;
        move_uploaded_file($_FILES["photo"]["tmp_name"], $photoPath);
      }

      // Password hash (MD5 to match your existing table)
      $password = password_hash($passwordRaw, PASSWORD_BCRYPT);

      // Insert record
      $sql = "INSERT INTO tblstaff 
                (StaffId, FullName, EmailId, MobileNumber, Password, Status, Address, IDProof, Photo, department_id, designation_id, Qualification, JoiningDate, degree_id, gender_id) 
                VALUES 
                (:StaffId, :fname, :email, :mobileno, :password, :status, :address, :idproof, :photo, :department_id, :designation_id, :qualification, :joiningdate, :degree_id, :gender_id)";
      $query = $dbh->prepare($sql);

      $query->bindParam(':StaffId', $StaffId, PDO::PARAM_STR);
      $query->bindParam(':fname', $fname, PDO::PARAM_STR);
      $query->bindParam(':email', $email, PDO::PARAM_STR);
      $query->bindParam(':mobileno', $mobileno, PDO::PARAM_STR);
      $query->bindParam(':password', $password, PDO::PARAM_STR);
      $query->bindParam(':status', $status, PDO::PARAM_INT);
      $query->bindParam(':address', $address, PDO::PARAM_STR);
      $query->bindParam(':idproof', $idProofPath, PDO::PARAM_STR);
      $query->bindParam(':photo', $photoPath, PDO::PARAM_STR);
      $query->bindParam(':department_id', $department_id, PDO::PARAM_INT);
      $query->bindParam(':designation_id', $designation_id, PDO::PARAM_INT);
      $query->bindParam(':qualification', $qualification, PDO::PARAM_STR);
      $query->bindParam(':joiningdate', $joiningDate, PDO::PARAM_STR);
      $query->bindParam(':degree_id', $degree_id, PDO::PARAM_INT);
      $query->bindParam(':gender_id', $gender_id, PDO::PARAM_INT);

      if ($query->execute()) {
        $_SESSION['success'] = 'Staff registration successful. You can now login.';
        header('Location: index.php');
        exit;
      } else {
        $_SESSION['error'] = 'Something went wrong. Please try again.';
      }
    }
  }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Staff Signup | Library System</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" type="image/x-icon" href="../assets/img/wisdomstack_logo.jpeg">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet" />
  <style>
    body {
      background: #fffcffff;
      font-family: 'Segoe UI', sans-serif;
    }

    .signup-wrapper {
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
    }

    .signup-box {
      background: #fff;
      border-radius: 15px;
      box-shadow: 0 8px 20px #b63f78ff;
      overflow: hidden;
      width: 100%;
      max-width: 900px;
      display: flex;
      flex-direction: row;
    }

    .promo-side {
      flex: 0 0 35%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .promo-side img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .form-side {
      padding: 40px 30px;
      flex: 1;
    }

    .form-side h3 {
      font-weight: bold;
      color: #4a62f2;
      margin-bottom: 25px;
      text-align: center;
    }

    .btn-submit {
      width: 100%;
      border-radius: 25px;
    }

    .form-label.required::after {
      content: " *";
      color: red;
      font-weight: bold;
    }


    @media (max-width: 768px) {
      .signup-box {
        flex-direction: column;
      }
    }
  </style>
</head>

<body>
  <div class="container-fluid signup-wrapper">
    <div class="signup-box">
      <div class="promo-side">
        <img src="../assets/img/stf_img4.jpg" alt="Staff Signup" />
      </div>

      <div class="form-side">
        <h3><i class="fas fa-user-plus me-2"></i>Staff Signup</h3>

        <?php if (!empty($_SESSION['error'])): ?>
          <div class="alert alert-danger"><?php echo $_SESSION['error'];
          unset($_SESSION['error']); ?></div>
        <?php endif; ?>

        <?php if (!empty($_SESSION['success'])): ?>
          <div class="alert alert-success"><?php echo $_SESSION['success'];
          unset($_SESSION['success']); ?></div>
        <?php endif; ?>

        <form name="signup" method="post" enctype="multipart/form-data">
          <div class="row">
            <div class="mb-3 col-md-6">
              <label class="form-label required">Staff ID</label>
              <input type="text" name="staffid" class="form-control" required />
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Full Name</label>
              <input type="text" name="fullname" class="form-control" required />
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Mobile Number</label>
              <input type="text" name="mobileno" maxlength="10" class="form-control" required />
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Email</label>
              <input type="email" name="email" class="form-control" required />
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Password</label>
              <input type="password" name="password" class="form-control" required />
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Confirm Password</label>
              <input type="password" name="confirmpassword" class="form-control" required />
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Address</label>
              <textarea name="address" class="form-control" rows="2" required></textarea>
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Qualification</label>
              <input type="text" name="qualification" class="form-control" required />
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Joining Date</label>
              <input type="date" name="joiningdate" class="form-control" required />
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Designation</label>
              <select name="designation_id" class="form-select" required>
                <option value="">Select Designation</option>
                <?php
                $sql = "SELECT designation_id, designation_name FROM tblstaffdesignation";
                foreach ($dbh->query($sql) as $row) {
                  echo "<option value='{$row['designation_id']}'>{$row['designation_name']}</option>";
                }
                ?>
              </select>
            </div>

            <div class="mb-3 col-md-4">
              <label class="form-label required">Gender</label>
              <select name="gender_id" class="form-select" required>
                <option value="">Select Gender</option>
                <?php
                $sql = "SELECT gender_id, gender_name FROM tblgender";
                foreach ($dbh->query($sql) as $row) {
                  echo "<option value='{$row['gender_id']}'>{$row['gender_name']}</option>";
                }
                ?>
              </select>
            </div>

            <div class="mb-3 col-md-4">
              <label class="form-label required">Department</label>
              <select name="department_id" class="form-select" required>
                <option value="">Select Department</option>
                <?php
                $sql = "SELECT department_id, department_name FROM tbldepartment";
                foreach ($dbh->query($sql) as $row) {
                  echo "<option value='{$row['department_id']}'>{$row['department_name']}</option>";
                }
                ?>
              </select>
            </div>

            <div class="mb-3 col-md-4">
              <label class="form-label required">Degree</label>
              <select name="degree_id" class="form-select" required>
                <option value="">Select Degree</option>
                <?php
                $sql = "SELECT degree_id, degree_name FROM tbldegree";
                foreach ($dbh->query($sql) as $row) {
                  echo "<option value='{$row['degree_id']}'>{$row['degree_name']}</option>";
                }
                ?>
              </select>
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Upload ID Proof</label>
              <input type="file" name="idproof" accept="image/*,application/pdf" class="form-control" required />
            </div>

            <div class="mb-3 col-md-6">
              <label class="form-label required">Upload Photo</label>
              <input type="file" name="photo" accept="image/*" class="form-control" required />
            </div>

            <div class="d-grid mt-3">
              <button type="submit" name="signup" class="btn btn-primary btn-submit">Signup</button>
            </div>
          </div>
        </form>

        <div class="mt-3 text-center">
          Already have an account? <a href="index.php">Login here</a>
        </div>
      </div>
    </div>
  </div>
</body>

</html>