<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require '../config.php';

if (!isset($_SESSION['user_id']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: index.php");
    exit;
}

$card_id     = (int)($_POST['card_id'] ?? 0);
$employee_id = (int)($_POST['employee_id'] ?? 0);
$card_number = trim($_POST['card_number'] ?? '');
$issue_date  = trim($_POST['issue_date'] ?? '');
$expiry_date = trim($_POST['expiry_date'] ?? '');
$status      = trim($_POST['status'] ?? 'Active');

if ($employee_id === 0 || empty($card_number) || empty($issue_date) || empty($expiry_date)) {
    $_SESSION['error'] = "Please fill in all required fields.";
    header("Location: " . ($card_id ? "edit.php?id={$card_id}" : "create.php"));
    exit;
}

if ($card_id > 0) {
    // Update existing card
    $stmt = $conn->prepare("UPDATE id_cards SET employee_id=?, card_number=?, issue_date=?, expiry_date=?, status=? WHERE id=?");
    $stmt->bind_param("issssi", $employee_id, $card_number, $issue_date, $expiry_date, $status, $card_id);
} else {
    // Insert new card
    $stmt = $conn->prepare("INSERT INTO id_cards (employee_id, card_number, issue_date, expiry_date, status) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("issss", $employee_id, $card_number, $issue_date, $expiry_date, $status);
}

if ($stmt->execute()) {
    $_SESSION['success'] = "ID Card record saved successfully.";
} else {
    $_SESSION['error'] = "Database error: " . $stmt->error;
}

header("Location: index.php");
exit;