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

if (!isset($_GET['id'])) {
    header("Location: admin_dashboard.php");
    exit();
}

$id = intval($_GET['id']);
$record = $conn->query("SELECT * FROM employee_records WHERE id = $id");

if (!$record || $record->num_rows !== 1) {
    echo "Record not found.";
    exit();
}

$row = $record->fetch_assoc();

// Handle update submission
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 = $row['photo']; // Keep old photo by default

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

        // Delete old photo if exists
        if ($photo_path && file_exists($photo_path)) {
            unlink($photo_path);
        }

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

        move_uploaded_file($tmp_name, $photo_path);
    }

    $stmt = $conn->prepare("UPDATE employee_records SET user_id = ?, name = ?, dob = ?, photo = ?, years_of_service = ?, remarks = ? WHERE id = ?");
    $stmt->bind_param("ssssisi", $user_id, $name, $dob, $photo_path, $years_of_service, $remarks, $id);

    if ($stmt->execute()) {
        header("Location: admin_dashboard.php?updated=1");
        exit();
    } else {
        echo "Update failed: " . $stmt->error;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Employee</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        img.thumb {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class="container mt-5">
    <h3>Edit Employee Record</h3>
    <form action="" method="POST" enctype="multipart/form-data" class="row g-3 mt-3">
        <div class="col-md-6">
            <label class="form-label">User ID</label>
            <input type="text" name="user_id" class="form-control" value="<?= htmlspecialchars($row['user_id']) ?>" required>
        </div>
        <div class="col-md-6">
            <label class="form-label">Full Name</label>
            <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($row['name']) ?>" required>
        </div>
        <div class="col-md-6">
            <label class="form-label">Date of Birth</label>
            <input type="date" name="dob" class="form-control" value="<?= $row['dob'] ?>" required>
        </div>
        <div class="col-md-6">
            <label class="form-label">Years of Service</label>
            <input type="number" name="years_of_service" class="form-control" value="<?= $row['years_of_service'] ?>" required>
        </div>
        <div class="col-md-12">
            <label class="form-label">Remarks</label>
            <textarea name="remarks" class="form-control" rows="3"><?= htmlspecialchars($row['remarks']) ?></textarea>
        </div>
        <div class="col-md-12">
            <label class="form-label">Current Photo</label><br>
            <?php if ($row['photo'] && file_exists($row['photo'])): ?>
                <img src="<?= $row['photo'] ?>" class="thumb mb-2">
            <?php else: ?>
                <p>No photo available.</p>
            <?php endif; ?>
            <input type="file" name="photo" class="form-control mt-2" accept="image/*">
            <small class="text-muted">Leave blank to keep current photo.</small>
        </div>
        <div class="col-12">
            <button type="submit" class="btn btn-success">Update Record</button>
            <a href="admin_dashboard.php" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
</div>
</body>
</html>
