<?php
// api/upload_payment_proof.php
// Upload a proof-of-payment file and link it to a ClientPayments row

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin', '*');
header('Access-Control-Allow-Methods', 'POST, OPTIONS');
header('Access-Control-Allow-Headers', 'Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    echo json_encode(['status' => 'ok']);
    exit;
}

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

require_once __DIR__ . '/../../config.php'; // public_html/api/../../config.php

// Validate payment_id
$paymentId = isset($_POST['payment_id']) ? (int)$_POST['payment_id'] : 0;
if ($paymentId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid or missing payment_id']);
    exit;
}

// Validate file
if (
    !isset($_FILES['proof']) ||
    !is_array($_FILES['proof']) ||
    $_FILES['proof']['error'] !== UPLOAD_ERR_OK
) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No file uploaded or upload error']);
    exit;
}

// Basic checks: size and extension
$file       = $_FILES['proof'];
$maxSize    = 5 * 1024 * 1024; // 5 MB
$allowedExt = ['jpg', 'jpeg', 'png', 'pdf'];

if ($file['size'] > $maxSize) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'File too large. Max 5 MB']);
    exit;
}

$originalName = basename($file['name']);
$ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExt, true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid file type']);
    exit;
}

/**
 * Build upload directory:
 * This script is at: /public_html/api/upload_payment_proof.php
 * Uploads should be in: /public_html/uploads/payments
 * => go up one level from api/ into uploads/payments
 */
$uploadDir = __DIR__ . '/../uploads/payments/';
if (!is_dir($uploadDir)) {
    // Ensure /uploads and /uploads/payments exist
    $baseUploads = __DIR__ . '/../uploads';
    if (!is_dir($baseUploads)) {
        mkdir($baseUploads, 0775, true);
    }
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0775, true);
    }
}
$uploadDir = rtrim($uploadDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

// Generate unique file name
$newName    = 'payment_' . $paymentId . '_' . time() . '.' . $ext;
$targetPath = $uploadDir . $newName;

// Move uploaded file
if (!move_uploaded_file($file['tmp_name'], $targetPath)) { // [web:10][web:13][web:34]
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to move uploaded file']);
    exit;
}

// Relative path for DB, as seen by web
$relativePath = 'uploads/payments/' . $newName;

try {
    // Ensure the payment exists
    $check = $pdo->prepare("SELECT Id FROM ClientPayments WHERE Id = :id LIMIT 1");
    $check->execute([':id' => $paymentId]);
    $row = $check->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        @unlink($targetPath);
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Payment not found']);
        exit;
    }

    // Update proof path - use ProofFilePath (your actual column)
    $stmt = $pdo->prepare("
        UPDATE ClientPayments
        SET ProofFilePath = :path
        WHERE Id = :id
    ");
    $stmt->execute([
        ':path' => $relativePath,
        ':id'   => $paymentId
    ]);

    echo json_encode([
        'success'   => true,
        'message'   => 'Proof uploaded successfully.',
        'paymentId' => $paymentId,
        'path'      => $relativePath
    ]);
} catch (Exception $e) {
    @unlink($targetPath);

    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save proof.',
        'details' => $e->getMessage()
    ]);
}
