<?php
header("Content-Type: application/json");
require_once "../config.php"; // database connection

$response = ["status" => "error", "message" => "Unknown error"];

try {
    // === POST data ===
    $StaffId       = $_POST['staffid'] ?? '';
    $FullName      = $_POST['fullname'] ?? '';
    $MobileNumber  = $_POST['mobileno'] ?? '';
    $EmailId       = $_POST['email'] ?? '';
    $PasswordRaw   = $_POST['password'] ?? '';
    $ConfirmPassword = $_POST['confirmpassword'] ?? '';
    $Address       = $_POST['address'] ?? '';
    $Qualification = $_POST['qualification'] ?? '';
    $gender_id     = $_POST['gender'] ?? null;
    $department_id = $_POST['department'] ?? null;
    $designation_id = $_POST['designation'] ?? null;
    $degree_id     = $_POST['degree'] ?? null;
    $JoiningDate   = $_POST['joiningDate'] ?? null;
    $Status        = 1;

    // === Validations ===
    if (empty($StaffId) || empty($FullName) || empty($EmailId) || empty($PasswordRaw)) {
        throw new Exception("All required fields must be filled.");
    }
    if ($PasswordRaw !== $ConfirmPassword) {
        throw new Exception("Passwords do not match.");
    }
    if (!filter_var($EmailId, FILTER_VALIDATE_EMAIL)) {
        throw new Exception("Invalid email format.");
    }
    if (!$gender_id || !$department_id || !$designation_id || !$degree_id) {
        throw new Exception("Please select Gender, Department, Designation, and Degree.");
    }

    // Check duplicate StaffId or Email
    $checkStmt = $dbh->prepare("SELECT StaffId FROM tblstaff WHERE StaffId = :sid OR EmailId = :email");
    $checkStmt->bindParam(':sid', $StaffId);
    $checkStmt->bindParam(':email', $EmailId);
    $checkStmt->execute();
    if ($checkStmt->rowCount() > 0) {
        throw new Exception("This Staff ID or Email is already registered.");
    }

    // === Hash password ===
    $Password = md5($PasswordRaw);

    // === Upload directories ===
    $baseUploadDir = 'C:' . DIRECTORY_SEPARATOR . 'wamp64' . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'staff' . DIRECTORY_SEPARATOR . 'uploads';
    $photoDir = $baseUploadDir . DIRECTORY_SEPARATOR . 'photos';
    $idDir    = $baseUploadDir . DIRECTORY_SEPARATOR . 'idproofs';

    if (!is_dir($photoDir)) mkdir($photoDir, 0777, true);
    if (!is_dir($idDir)) mkdir($idDir, 0777, true);

    // === File names and paths ===
    $photoName = basename($_FILES['photo']['name']);
    $idName    = basename($_FILES['idProof']['name']);

    $targetPhoto = $photoDir . DIRECTORY_SEPARATOR . $photoName;
    $targetId    = $idDir . DIRECTORY_SEPARATOR . $idName;

    // Relative paths to store in DB
    $photoDBPath = 'uploads/photos/' . $photoName;
    $idDBPath    = 'uploads/idproofs/' . $idName;

    // === Move uploaded files ===
    if (!move_uploaded_file($_FILES['photo']['tmp_name'], $targetPhoto)) {
        throw new Exception('Failed to save photo. Check folder permissions.');
    }
    if (!move_uploaded_file($_FILES['idProof']['tmp_name'], $targetId)) {
        throw new Exception('Failed to save ID proof. Check folder permissions.');
    }

    // === Insert into database ===
    $sql = "INSERT INTO tblstaff
        (StaffId, FullName, MobileNumber, EmailId, Password, Address, Qualification,
         gender_id, department_id, designation_id, degree_id, JoiningDate, Status, IDProof, Photo)
        VALUES
        (:StaffId, :FullName, :MobileNumber, :EmailId, :Password, :Address, :Qualification,
         :gender_id, :department_id, :designation_id, :degree_id, :JoiningDate, :Status, :idProof, :photo)";

    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':StaffId', $StaffId);
    $stmt->bindParam(':FullName', $FullName);
    $stmt->bindParam(':MobileNumber', $MobileNumber);
    $stmt->bindParam(':EmailId', $EmailId);
    $stmt->bindParam(':Password', $Password);
    $stmt->bindParam(':Address', $Address);
    $stmt->bindParam(':Qualification', $Qualification);
    $stmt->bindParam(':gender_id', $gender_id, PDO::PARAM_INT);
    $stmt->bindParam(':department_id', $department_id, PDO::PARAM_INT);
    $stmt->bindParam(':designation_id', $designation_id, PDO::PARAM_INT);
    $stmt->bindParam(':degree_id', $degree_id, PDO::PARAM_INT);
    $stmt->bindParam(':JoiningDate', $JoiningDate);
    $stmt->bindParam(':idProof', $idDBPath);
    $stmt->bindParam(':photo', $photoDBPath);
    $stmt->bindParam(':Status', $Status, PDO::PARAM_INT);

    if ($stmt->execute()) {
        $response = ["status" => "success", "message" => "Staff registered successfully."];
    } else {
        throw new Exception("Failed to insert staff record.");
    }
} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
}

echo json_encode($response);
exit;
