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

if (isset($_POST['signup'])) {
  $StudentId = trim($_POST['studentid']);
  $fname = trim($_POST['fullname']);
  $mobileno = trim($_POST['mobileno']);
  $email = trim($_POST['email']);
  $passwordRaw = $_POST['password'];
  $confirmPwd = $_POST['confirmpassword'];
  $address = trim($_POST['address']);
  $year_start = trim($_POST['year_start']);
  $year_end = trim($_POST['year_end']);
  $passed_out_year = "$year_start-$year_end";
  $status = 2;

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

  // Validations
  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 ($year_start > $year_end) {
    $_SESSION['error'] = 'Start year cannot be after end year.';
  } elseif (empty($_POST['gender_id']) || empty($_POST['department_id']) || empty($_POST['degree_id']) || empty($_POST['shift'])) {
    $_SESSION['error'] = 'Please select Gender, Department, Shift and Degree.';
  } else {
    $gender_id = intval($_POST['gender_id']);
    $department_id = intval($_POST['department_id']);
    $degree_id = intval($_POST['degree_id']);
    $shift = intval($_POST['shift']);

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

    if ($checkStmt->rowCount() > 0) {
      $_SESSION['error'] = 'This Student ID is already registered.';
    } else {
      // Create upload 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);
      }

      // Hash password securely
      // $password = password_hash($passwordRaw, PASSWORD_DEFAULT);
      $password = password_hash($passwordRaw, PASSWORD_BCRYPT);


      // Insert record
      $sql = "INSERT INTO tblstudents 
                (StudentId, FullName, MobileNumber, EmailId, Password, Address, IDProof, Photo, Status, passed_out_year, gender_id, shift, department_id, degree_id) 
                VALUES 
                (:StudentId, :fname, :mobileno, :email, :password, :address, :idproof, :photo, :status, :passed_out_year, :gender_id, :shift, :department_id, :degree_id)";
      $query = $dbh->prepare($sql);

      $query->bindParam(':StudentId', $StudentId, PDO::PARAM_STR);
      $query->bindParam(':fname', $fname, PDO::PARAM_STR);
      $query->bindParam(':mobileno', $mobileno, PDO::PARAM_STR);
      $query->bindParam(':email', $email, PDO::PARAM_STR);
      $query->bindParam(':password', $password, PDO::PARAM_STR);
      $query->bindParam(':address', $address, PDO::PARAM_STR);
      $query->bindParam(':idproof', $idProofPath, PDO::PARAM_STR);
      $query->bindParam(':photo', $photoPath, PDO::PARAM_STR);
      $query->bindParam(':status', $status, PDO::PARAM_INT);
      $query->bindParam(':passed_out_year', $passed_out_year, PDO::PARAM_STR);
      $query->bindParam(':gender_id', $gender_id, PDO::PARAM_INT);
      $query->bindParam(':shift', $shift, PDO::PARAM_INT);
      $query->bindParam(':department_id', $department_id, PDO::PARAM_INT);
      $query->bindParam(':degree_id', $degree_id, PDO::PARAM_INT);

      if ($query->execute()) {
        $_SESSION['success'] = '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>Student 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">

  <!-- Bootstrap 5 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <!-- Font Awesome -->
  <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%;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
    }

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

    .form-side {
      padding: 40px 30px;
      flex: 0 0 65%;
    }

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

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

    .form-text {
      font-size: 0.85rem;
    }

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


    @media (max-width: 768px) {
      .signup-box {
        flex-direction: column;
      }
    }
  </style>
  <script>
    function validateForm() {
      const form = document.forms["signup"];
      const pw = form["password"];
      const cpw = form["confirmpassword"];
      const email = form["email"];
      const yearStart = form["year_start"];
      const yearEnd = form["year_end"];
      const gender = form["gender_id"];
      const shift = form["shift"];
      const dept = form["department_id"];
      const degree = form["degree_id"];
      const strongPwd = /^(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{6,}$/;

      if (pw.value !== cpw.value) {
        alert("Passwords do not match!");
        cpw.focus();
        return false;
      }

      if (!strongPwd.test(pw.value)) {
        alert("Password must be at least 6 characters, include an uppercase letter and a special character.");
        pw.focus();
        return false;
      }

      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)) {
        alert("Invalid email format.");
        email.focus();
        return false;
      }

      if (yearStart.value === "" || yearEnd.value === "") {
        alert("Please select both start and end years.");
        yearStart.focus();
        return false;
      }

      if (parseInt(yearStart.value) > parseInt(yearEnd.value)) {
        alert("Start year cannot be greater than end year.");
        yearStart.focus();
        return false;
      }

      if (gender.value === "") {
        alert("Please select Gender.");
        gender.focus();
        return false;
      }

      if (shift.value === "") {
        alert("Please select Shift.");
        shift.focus();
        return false;
      }

      if (dept.value === "") {
        alert("Please select Department.");
        dept.focus();
        return false;
      }

      if (degree.value === "") {
        alert("Please select Degree.");
        degree.focus();
        return false;
      }

      return true;
    }
  </script>
</head>

<body>
  <div class="container-fluid signup-wrapper">
    <div class="signup-box">
      <div class="promo-side p-0">
        <img src="assets/img/lms_img7.AVIF" alt="Library Signup" />
      </div>

      <div class="form-side">
        <h3><i class="fas fa-user-plus me-2"></i>Student 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" onsubmit="return validateForm();" enctype="multipart/form-data">
          <div class="row">
            <div class="mb-3 col-md-6">
              <label class="form-label required">Student ID</label>
              <input type="text" name="studentid" 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 class="form-text">Min 6 chars, at least 1 uppercase & 1 special char</div>
            </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-3">
              <label class="form-label required">Academic Year (Start)</label>
              <select name="year_start" class="form-select" required>
                <option value="">Select</option>
                <?php
                $currentYear = (int) date('Y');
                for ($i = $currentYear; $i >= 1980; $i--) {
                  echo "<option value='{$i}'>{$i}</option>";
                }
                ?>
              </select>
            </div>

            <div class="mb-3 col-md-3">
              <label class="form-label required">Academic Year (End)</label>
              <select name="year_end" class="form-select" required>
                <option value="">Select</option>
                <?php
                for ($i = $currentYear + 10; $i >= 1980; $i--) {
                  echo "<option value='{$i}'>{$i}</option>";
                }
                ?>
              </select>
            </div>

            <div class="mb-3 col-md-4">
              <label class="form-label required">Shift</label>
              <select name="shift" class="form-select" required>
                <option value="">Select Shift</option>
                <option value="1">Shift I</option>
                <option value="2">Shift II</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>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>