<?php
require 'db.php';
require 'auth.php';
require_login();

header('Content-Type: application/json');

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

$id = intval($_POST['id'] ?? 0);
$keterangan = trim($_POST['keterangan'] ?? '');

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'ID tidak valid']);
    exit;
}

// Check if peminjaman exists
$stmt = $db->prepare("SELECT * FROM peminjaman WHERE id = ?");
$stmt->execute([$id]);
$peminjaman = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$peminjaman) {
    echo json_encode(['success' => false, 'message' => 'Data peminjaman tidak ditemukan']);
    exit;
}

// Validate file upload
if (!isset($_FILES['dokumen']) || $_FILES['dokumen']['error'] !== UPLOAD_ERR_OK) {
    $errorMsg = 'File tidak ditemukan atau error saat upload';
    if (isset($_FILES['dokumen']['error'])) {
        switch ($_FILES['dokumen']['error']) {
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                $errorMsg = 'Ukuran file terlalu besar';
                break;
            case UPLOAD_ERR_NO_FILE:
                $errorMsg = 'Tidak ada file yang diupload';
                break;
        }
    }
    echo json_encode(['success' => false, 'message' => $errorMsg]);
    exit;
}

$file = $_FILES['dokumen'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];

// Validate file size (max 5MB)
if ($fileSize > 5 * 1024 * 1024) {
    echo json_encode(['success' => false, 'message' => 'Ukuran file terlalu besar. Maksimal 5MB']);
    exit;
}

// Validate file extension
$allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png'];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

if (!in_array($fileExtension, $allowedExtensions)) {
    echo json_encode(['success' => false, 'message' => 'Format file tidak diizinkan. Hanya PDF, JPG, PNG']);
    exit;
}

// Validate mime type
$allowedMimeTypes = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$fileMimeType = finfo_file($finfo, $fileTmpName);
finfo_close($finfo);

if (!in_array($fileMimeType, $allowedMimeTypes)) {
    echo json_encode(['success' => false, 'message' => 'Tipe file tidak valid']);
    exit;
}

// Create upload directory if not exists
$uploadDir = 'uploads/dokumen/';
if (!is_dir($uploadDir)) {
    if (!mkdir($uploadDir, 0755, true)) {
        echo json_encode(['success' => false, 'message' => 'Gagal membuat direktori upload']);
        exit;
    }
}

// Generate unique filename
$newFileName = 'dok_' . $id . '_' . time() . '.' . $fileExtension;
$uploadPath = $uploadDir . $newFileName;

// Delete old file if exists
if (!empty($peminjaman['dokumen_path']) && file_exists($peminjaman['dokumen_path'])) {
    @unlink($peminjaman['dokumen_path']);
}

// Move uploaded file
if (!move_uploaded_file($fileTmpName, $uploadPath)) {
    echo json_encode(['success' => false, 'message' => 'Gagal menyimpan file']);
    exit;
}

// Save to database - dokumen_history table (multiple uploads support)
try {
    $waktuUpload = date('Y-m-d H:i:s');
    $uploadedBy = $_SESSION['user']['nama_lengkap'] ?? $_SESSION['user']['username'] ?? 'Unknown';
    
    // Insert to dokumen_history table
    $insertStmt = $db->prepare("INSERT INTO dokumen_history (peminjaman_id, dokumen_path, dokumen_keterangan, uploaded_by, uploaded_at) VALUES (?, ?, ?, ?, ?)");
    $insertStmt->execute([$id, $uploadPath, $keterangan, $uploadedBy, $waktuUpload]);
    
    // Also update peminjaman table with latest document for backward compatibility
    $updateStmt = $db->prepare("UPDATE peminjaman SET dokumen_path = ?, dokumen_keterangan = ?, dokumen_upload_at = ? WHERE id = ?");
    $updateStmt->execute([$uploadPath, $keterangan, $waktuUpload, $id]);
    
    echo json_encode([
        'success' => true, 
        'message' => 'Dokumen berhasil diupload!',
        'file_path' => $uploadPath
    ]);
} catch (Exception $e) {
    // Delete uploaded file if database update fails
    if (file_exists($uploadPath)) {
        @unlink($uploadPath);
    }
    echo json_encode(['success' => false, 'message' => 'Gagal menyimpan ke database: ' . $e->getMessage()]);
}
