<?php
session_start();

// ✅ Database connection (update credentials if needed)
$con = mysqli_connect('localhost', 'hmrsaasc_cert765', 'hmrsaasc_cert765', 'hmrsaasc_cert765');
if (!$con) {
    die("Server Connection Failed: " . mysqli_connect_error());
}

// ✅ Collect form data safely
$name       = trim($_POST['name']);
$email      = trim($_POST['email']);
$post       = trim($_POST['post']);
$start_date = trim($_POST['Start_date']);
$end_date   = trim($_POST['end_date']);

// ✅ Validate basic fields
if (empty($name) || empty($email) || empty($post) || empty($start_date) || empty($end_date)) {
    echo "<script>
    alert('Please fill in all fields.');
    window.location.href='http://localhost/cert/Register';
    </script>";
    exit();
}

// ✅ Handle passport upload
$upload_dir = __DIR__ . "/uploads/";  // Absolute path for server reliability
$relative_path = "uploads/";          // For storing relative path in DB

// Create folder if missing
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

if (isset($_FILES['passport']) && $_FILES['passport']['error'] === UPLOAD_ERR_OK) {

    $passport_name = basename($_FILES['passport']['name']);
    $passport_tmp  = $_FILES['passport']['tmp_name'];
    $file_ext      = strtolower(pathinfo($passport_name, PATHINFO_EXTENSION));

    $allowed_ext = ['jpg', 'jpeg', 'png'];
    if (in_array($file_ext, $allowed_ext)) {

        // Create safe unique filename
        $new_filename  = time() . "_" . preg_replace("/[^a-zA-Z0-9.]/", "_", $passport_name);
        $passport_path = $upload_dir . $new_filename;   // Full server path
        $db_path       = $relative_path . $new_filename; // Relative DB path

        if (move_uploaded_file($passport_tmp, $passport_path)) {

            // ✅ Insert details into DB
            $q = "INSERT INTO intern (NAME, EMAIL, POST, START_DATE, END_DATE, PASSPORT)
                  VALUES ('$name', '$email', '$post', '$start_date', '$end_date', '$db_path')";

            if (mysqli_query($con, $q)) {
                echo "<script>
                alert('✅ Successfully entered details');
                window.location.href='http://localhost/cert/Register';
                </script>";
            } else {
                echo "<script>
                alert('❌ Database insert failed: " . mysqli_error($con) . "');
                window.location.href='http://localhost/cert/Register';
                </script>";
            }
        } else {
            echo "<script>
            alert('❌ File upload failed. Please try again.');
            window.location.href='http://localhost/cert/Register';
            </script>";
        }
    } else {
        echo "<script>
        alert('❌ Invalid file type. Only JPG, JPEG, PNG allowed.');
        window.location.href='http://localhost/cert/Register';
        </script>";
    }
} else {
    echo "<script>
    alert('❌ No file selected or upload error.');
    window.location.href='http://localhost/cert/Register';
    </script>";
}
?>
