<?php
include '../config.php';  // has $conn (mysqli)

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

$customer_id = intval($_POST['customer_id'] ?? 0);
$loan_id     = intval($_POST['loan_id'] ?? 0);
$date        = $_POST['date'] ?? date('Y-m-d');

if (!isset($_FILES['document'])) {
    echo json_encode(['success'=>false,'message'=>'No file uploaded']);
    exit;
}

$uploadDir = __DIR__ . '/../uploads/documents/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$file     = $_FILES['document'];
$tmpPath  = $file['tmp_name'];
$origName = basename($file['name']);
$ext      = pathinfo($origName, PATHINFO_EXTENSION);
$newName  = uniqid('doc_') . '.' . $ext;
$destPath = $uploadDir . $newName;

if (!move_uploaded_file($tmpPath, $destPath)) {
    echo json_encode(['success'=>false,'message'=>'Failed to move uploaded file']);
    exit;
}

// Save record
$docPath = 'uploads/documents/' . $newName;
$sql = "INSERT INTO `documents`
        (`customer_id`,`loan_id`,`document_path`,`date`)
        VALUES
        ($customer_id, $loan_id, '{$docPath}', '{$date}')";
if (mysqli_query($conn, $sql)) {
    echo json_encode(['success'=>true,'message'=>'Uploaded and saved']);
} else {
    // rollback file?
    unlink($destPath);
    echo json_encode(['success'=>false,'message'=>'DB error: '.mysqli_error($conn)]);
}
