<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.html");
    exit();
}
require_once 'connection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $dob = $_POST['dob'];
    $years_of_service = (int) $_POST['years_of_service'];
    $remarks = mysqli_real_escape_string($conn, $_POST['remarks']);

    $photo_path = NULL;

    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = 'uploads/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        $file_tmp = $_FILES['photo']['tmp_name'];
        $file_name = basename($_FILES['photo']['name']);
        $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
        $new_filename = uniqid('img_') . '.' . $file_ext;
        $target_path = $upload_dir . $new_filename;

        if (move_uploaded_file($file_tmp, $target_path)) {
            $photo_path = $target_path;
        }
    }

    $stmt = $conn->prepare("INSERT INTO employee_records (user_id, name, dob, photo, years_of_service, remarks) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssis", $user_id, $name, $dob, $photo_path, $years_of_service, $remarks);
    
    if ($stmt->execute()) {
        header("Location: admin_dashboard.php?success=1");
        exit();
    } else {
        echo "Error: " . $stmt->error;
    }
}
?>
