<?php
require_once __DIR__ . '/../auth.php';
requireLogin();
require_once __DIR__ . '/../config.php';
if (function_exists('require_csrf')) require_csrf();

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['image'])) {
    echo json_encode(['success' => false, 'message' => 'لم يتم رفع صورة']);
    exit;
}
if (!canEdit()) {
    echo json_encode(['success' => false, 'message' => 'غير مسموح']);
    exit;
}

$invoice = preg_replace('/[^a-zA-Z0-9_-]/', '', trim($_POST['invoice_number'] ?? ''));
if ($invoice === '') {
    $invoice = 'img';
}

// مجلد الشهر: مثال 2jan2026 أو 10mar2025 (يوم+شهر+سنة)
$months = ['', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
$monthFolder = date('j') . $months[(int)date('n')] . date('Y');
$uploadDir = UPLOADS_PATH . $monthFolder . '/';

if (!is_dir(UPLOADS_PATH)) mkdir(UPLOADS_PATH, 0755);
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755);

$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
if (!in_array($ext, $allowed)) {
    echo json_encode(['success' => false, 'message' => 'صيغة غير مدعومة']);
    exit;
}

$max_size = 5 * 1024 * 1024; // 5MB
if ($_FILES['image']['size'] > $max_size) {
    echo json_encode(['success' => false, 'message' => 'حجم الملف يتجاوز 5 ميجا']);
    exit;
}

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['image']['tmp_name']);
finfo_close($finfo);
$allowed_mimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($mime, $allowed_mimes)) {
    echo json_encode(['success' => false, 'message' => 'نوع الملف غير مسموح']);
    exit;
}

$filename = $invoice . '_' . time() . '.' . $ext;
$filepath = $uploadDir . $filename;
$relativePath = $monthFolder . '/' . $filename;

if (move_uploaded_file($_FILES['image']['tmp_name'], $filepath)) {
    echo json_encode(['success' => true, 'path' => $relativePath]);
} else {
    echo json_encode(['success' => false, 'message' => 'فشل الرفع']);
}
