<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);

// إعدادات الـ Headers
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');

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

if (!isset($_FILES['file'])) {
    http_response_code(400);
    echo json_encode(['error' => 'No file uploaded']);
    exit;
}

$type = isset($_POST['type']) ? $_POST['type'] : 'general';
$upload_dir = 'uploads/' . basename($type) . '/';

if (!is_dir($upload_dir)) {
    @mkdir($upload_dir, 0777, true);
}

$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_error = $file['error'];

if ($file_error !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['error' => 'File upload error code: ' . $file_error]);
    exit;
}

$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$allowed_exts = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'xls', 'xlsx', 'csv', 'doc', 'docx'];

if (!in_array($file_ext, $allowed_exts)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid file extension']);
    exit;
}

$new_file_name = uniqid() . '_' . time() . '.' . $file_ext;
$target_file = $upload_dir . $new_file_name;

if (@move_uploaded_file($file_tmp, $target_file)) {
    echo json_encode([
        'success' => true,
        'path' => $target_file,
        'name' => $file_name
    ]);
} else {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to save file']);
}
?>