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

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

try {
    // === Inputs from Flutter ===
    $StudentId  = trim($_POST['studentid'] ?? '');
    $fname      = trim($_POST['fullname'] ?? '');
    $mobileno   = trim($_POST['mobileno'] ?? '');
    $email      = trim($_POST['email'] ?? '');
    $pwdRaw     = $_POST['password'] ?? '';
    $pwd2       = $_POST['confirmpassword'] ?? '';
    $address    = trim($_POST['address'] ?? '');
    $gender     = $_POST['gender'] ?? '';
    $dept       = $_POST['department'] ?? '';
    $degree     = $_POST['degree'] ?? '';
    $year       = $_POST['yearRange'] ?? '';

    // === Validate required fields ===
    if (
        empty($StudentId) || empty($fname) || empty($mobileno) || empty($email) ||
        empty($pwdRaw) || empty($pwd2) || empty($address) || empty($gender) ||
        empty($dept) || empty($degree) || empty($year) ||
        empty($_FILES['photo']['name']) || empty($_FILES['idProof']['name'])
    ) {
        throw new Exception('All required fields must be filled.');
    }

    // === Check if StudentId already exists ===
    $chk = $dbh->prepare('SELECT StudentId FROM tblstudents WHERE StudentId = :sid');
    $chk->bindParam(':sid', $StudentId);
    $chk->execute();
    $result = $chk->fetch(PDO::FETCH_OBJ);
    if ($chk->rowCount() > 0) {
        throw new Exception('This Student ID is already registered.');
    }

    // === Hash password ===
    $password = md5($pwdRaw); // For production, use password_hash()

    // === Upload directory ===
    // $uploadDir = 'C:' . DIRECTORY_SEPARATOR . 'wamp64' . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'uploads';

    // $photoDir = $uploadDir . DIRECTORY_SEPARATOR . 'photos';
    // $idDir    = $uploadDir . DIRECTORY_SEPARATOR . 'idproofs';

    $photoDir = "../" . $result->Photo;
    $idDir    = "../" . $result->idproofs;

    // Create folders if not exist
    if (!is_dir($photoDir)) mkdir($photoDir, 0777, true);
    if (!is_dir($idDir)) mkdir($idDir, 0777, true);

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

    // Absolute paths for saving
    $targetPhoto = $photoDir . DIRECTORY_SEPARATOR . $photoName;
    $targetId    = $idDir . DIRECTORY_SEPARATOR . $idName;

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

    // Move 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 record ===
    $sql = "INSERT INTO tblstudents
        (StudentId, FullName, EmailId, MobileNumber, Password, Status, Address,
         passed_out_year, gender_id, department_id, degree_id, IDProof, Photo)
        VALUES
        (:studentid, :fullname, :email, :mobileno, :password, :status, :address,
         :year, :gender, :dept, :degree, :idProof, :photo)";

    $stmt = $dbh->prepare($sql);
    $status = 2;

    $stmt->bindParam(':studentid', $StudentId);
    $stmt->bindParam(':fullname', $fname);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':mobileno', $mobileno);
    $stmt->bindParam(':password', $password);
    $stmt->bindParam(':status', $status);
    $stmt->bindParam(':address', $address);
    $stmt->bindParam(':year', $year);
    $stmt->bindParam(':gender', $gender);
    $stmt->bindParam(':dept', $dept);
    $stmt->bindParam(':degree', $degree);
    $stmt->bindParam(':idProof', $idDBPath);
    $stmt->bindParam(':photo', $photoDBPath);

    if ($stmt->execute()) {
        $response = ['status' => 'success', 'message' => 'Registration successful'];
    } else {
        throw new Exception('Database insert failed');
    }
} catch (Exception $e) {
    $response = ['status' => 'error', 'message' => $e->getMessage()];
}

echo json_encode($response);
exit;
