<?php
error_reporting(E_ALL);
ini_set('display_errors', 0); // Disable direct display to prevent broken JSON output
header('Content-Type: application/json');

session_start();
session_write_close();
require '../config.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

$employee_id = (int)($_GET['employee_id'] ?? $_POST['employee_id'] ?? 0);

if ($employee_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid Employee ID provided.']);
    exit;
}

// 1. Check if employee exists
$stmt = $conn->prepare("SELECT id, employee_no FROM employees WHERE id = ?");
$stmt->bind_param("i", $employee_id);
$stmt->execute();
$emp = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$emp) {
    echo json_encode(['success' => false, 'message' => 'Employee record not found.']);
    exit;
}

// 2. Check if card already exists
$stmt_check = $conn->prepare("SELECT id FROM id_cards WHERE employee_id = ?");
$stmt_check->bind_param("i", $employee_id);
$stmt_check->execute();
$existing_card = $stmt_check->get_result()->fetch_assoc();
$stmt_check->close();

if ($existing_card) {
    echo json_encode(['success' => false, 'message' => 'ID Card already issued for this employee.']);
    exit;
}

// 3. Generate unique card number and issue dates
$card_number = 'CRD-' . strtoupper(substr(md5(uniqid((string)mt_rand(), true)), 0, 8));
$issue_date  = date('Y-m-d');
$expiry_date = date('Y-m-d', strtotime('+2 years'));
$status      = 'Active';

// 4. Insert into id_cards table
$stmt_insert = $conn->prepare("INSERT INTO id_cards (employee_id, card_number, status, issue_date, expiry_date) VALUES (?, ?, ?, ?, ?)");
$stmt_insert->bind_param("issss", $employee_id, $card_number, $status, $issue_date, $expiry_date);

if ($stmt_insert->execute()) {
    $card_id = $stmt_insert->insert_id;
    $stmt_insert->close();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Smart ID Card successfully generated!',
        'card_id' => $card_id,
        'card_number' => $card_number,
        'status' => $status
    ]);
    exit;
} else {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit;
}