<?php
include('include/headscript.php');

// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);

// Controlla la connessione al database
if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => "Connection failed: " . $conn->connect_error]));
}

// Impostazioni della cartella di destinazione
$targetDir = "persondocuments/";

// Recupera i dati inviati tramite POST e FILES
$owner_id = isset($_POST['owner_id']) ? intval($_POST['owner_id']) : 0; // `owner_id` dell'owner
$document_id = isset($_POST['document_id']) ? intval($_POST['document_id']) : 0;
$file = isset($_FILES['file']) ? $_FILES['file'] : null;
$expirydate = isset($_POST['expirydate']) ? $_POST['expirydate'] : null;
$note = isset($_POST['note']) ? $_POST['note'] : null;

// Validazione dei dati
if ($owner_id === 0 || $document_id === 0 || !$file) {
    echo json_encode(['success' => false, 'message' => "Invalid input data."]);
    exit;
}

// Controlla se il file è stato caricato correttamente
if ($file['error'] === UPLOAD_ERR_OK) {
    // Rinomina il file con lo schema ownerId-timestamp-filename
    $filename = basename($file['name']);
    $fileExtension = pathinfo($filename, PATHINFO_EXTENSION);
    $newFilename = $owner_id . '-' . time() . '-' . $filename;
    $targetFilePath = $targetDir . $newFilename;

    // Verifica e crea la cartella se non esiste
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    // Sposta il file nella cartella di destinazione
    if (move_uploaded_file($file['tmp_name'], $targetFilePath)) {
        // Determina lo stato di scadenza
        $expiry_status = ($expirydate) ? 1 : 0;

        // Inserisce il file nel database
        $query = "
            INSERT INTO doc_storage (idhome, owner_id, document_id, filename, expirystatus, expirydate, note, created_at, updated_at)
            VALUES (NULL, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        ";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("iissss", $owner_id, $document_id, $newFilename, $expiry_status, $expirydate, $note);

        if ($stmt->execute()) {
            // Ottieni l'ID del documento appena inserito
            $documentId = $stmt->insert_id;

            // Ottieni la data di caricamento dal database
            $stmtSelect = $conn->prepare("SELECT created_at FROM doc_storage WHERE id = ?");
            $stmtSelect->bind_param("i", $documentId);
            $stmtSelect->execute();
            $result = $stmtSelect->get_result();
            $row = $result->fetch_assoc();
            $uploadDate = $row['created_at'];
            $stmtSelect->close();

            echo json_encode([
                'success' => true,
                'message' => "File uploaded successfully.",
                'fileName' => $newFilename,
                'uploadDate' => $uploadDate,
                'documentId' => $documentId
            ]);
        } else {
            // Rimuove il file se l'inserimento nel DB fallisce
            unlink($targetFilePath);
            echo json_encode(['success' => false, 'message' => "Failed to insert into database: " . $stmt->error]);
        }

        $stmt->close();
    } else {
        echo json_encode(['success' => false, 'message' => "Failed to move the file."]);
    }
} else {
    echo json_encode(['success' => false, 'message' => "File upload error."]);
}

$conn->close();
