<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid Request Method']);
    exit;
}

$emp_id = $_SESSION['emp_id'];
$category = $_POST['category'] ?? '';
$document_type = $_POST['document_type'] ?? '';
$document_number = $_POST['document_number'] ?? null;

// Basic Validation
if (empty($category) || empty($document_type)) {
    echo json_encode(['success' => false, 'message' => 'Missing category or document type']);
    exit;
}

if (!isset($_FILES['document_file']) || $_FILES['document_file']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'File upload failed or missing file']);
    exit;
}

$file = $_FILES['document_file'];
$allowed_types = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
$max_size = 10 * 1024 * 1024; // 10MB

// Validate Type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!in_array($mime_type, $allowed_types)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file format. Only PDF, JPG, PNG allowed.']);
    exit;
}

// Validate Size
if ($file['size'] > $max_size) {
    echo json_encode(['success' => false, 'message' => 'File exceeds 10MB size limit.']);
    exit;
}

// Ensure Upload Directory Exists
$upload_dir = __DIR__ . '/../uploads/documents/';
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Secure Naming: EMP1024_Aadhaar_Card_16834020.pdf
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$safe_doc_type = preg_replace('/[^a-zA-Z0-9]+/', '_', $document_type);
$new_filename = 'EMP' . $emp_id . '_' . $safe_doc_type . '_' . time() . '.' . $ext;
$target_path = $upload_dir . $new_filename;

// Move File
if (!move_uploaded_file($file['tmp_name'], $target_path)) {
    echo json_encode(['success' => false, 'message' => 'Server error: Could not save file.']);
    exit;
}

// DB Insertion or Update
$db = getDB();

// Check if document type already exists for employee
$stmt = $db->prepare("SELECT doc_id, file_url FROM employee_documents WHERE employee_id = ? AND document_type = ?");
$stmt->execute([$emp_id, $document_type]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC);

try {
    $db->beginTransaction();
    
    if ($existing) {
        // Update existing record
        $update = $db->prepare("UPDATE employee_documents SET file_url = ?, document_number = ?, status = 'Submitted', uploaded_at = NOW(), remarks = 'Re-uploaded by employee' WHERE doc_id = ?");
        $update->execute([$new_filename, $document_number, $existing['doc_id']]);
        $doc_id = $existing['doc_id'];
        
        // Remove old file to save space
        if (file_exists($upload_dir . $existing['file_url'])) {
            unlink($upload_dir . $existing['file_url']);
        }
    } else {
        // Insert new record
        $insert = $db->prepare("INSERT INTO employee_documents (employee_id, category, document_type, document_number, file_url, status) VALUES (?, ?, ?, ?, ?, 'Submitted')");
        $insert->execute([$emp_id, $category, $document_type, $document_number, $new_filename]);
        $doc_id = $db->lastInsertId();
    }
    
    // Log Action
    $log = $db->prepare("INSERT INTO verification_logs (doc_id, verified_by, action, comments) VALUES (?, ?, 'Upload', 'Employee uploaded document')");
    $log->execute([$doc_id, $emp_id]); // Employee ID is used as verified_by here since they initiated the action

    $db->commit();
    echo json_encode(['success' => true, 'message' => 'Document uploaded successfully', 'file' => $new_filename]);

} catch (Exception $e) {
    $db->rollBack();
    // Delete uploaded file if DB fails
    if (file_exists($target_path)) {
        unlink($target_path);
    }
    echo json_encode(['success' => false, 'message' => 'Database Error: ' . $e->getMessage()]);
}
