<?php
ini_set('display_errors', '1'); 
ini_set('display_startup_errors', '1'); 
error_reporting(E_ALL);
include('db.php');

$referral_id = isset($_REQUEST['referral_id']) ? base64_decode($_REQUEST['referral_id']) : '';
$response = ['status' => 0, 'referral_id' => '', 'total_files' => 0, 'message' => ''];

if (!empty($referral_id) && !empty($_FILES['xray_files'])) {
    
    $uploaded_paths = [];
    $file_count = count($_FILES['xray_files']['name']);
    
    // --- 1. Process New Files ---
    for ($i = 0; $i < $file_count; $i++) {
        
        if ($_FILES['xray_files']['error'][$i] !== UPLOAD_ERR_OK) {
            continue; 
        }
        
        // File processing/naming logic (same as before)
        $file_basename = pathinfo($_FILES["xray_files"]["name"][$i], PATHINFO_FILENAME);
        $file_ext = strtolower(pathinfo($_FILES["xray_files"]["name"][$i], PATHINFO_EXTENSION)); // <-- CORRECTION HERE
        $sanitized_name = trim(preg_replace("/-+/", "-", preg_replace("/[^a-z0-9]+/", "-", strtolower($file_basename))), "-");
        $filename = $sanitized_name . "-" . substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8) . "." . $file_ext;
        
        $destination_path = $_SERVER['DOCUMENT_ROOT'] . '/code/uploads/' . $filename;
        $db_path = '/code/uploads/' . $filename;

        if (move_uploaded_file($_FILES['xray_files']['tmp_name'][$i], $destination_path)) {
            $uploaded_paths[] = $db_path;
        }
    }

    if (!empty($uploaded_paths)) {
        
        // --- 2. Fetch Existing Files ---
        // Fetch existing files for APPRENDING (safest approach)
        $query = $db->query("SELECT attachment FROM wp_referral_form WHERE id = " . $referral_id);
        $data = $query->fetch();
        $existing_attachments = $data && !empty($data['attachment']) ? array_filter(explode(',', $data['attachment'])) : [];

        // --- 3. Merge and Update ---
        $all_attachments = array_merge($existing_attachments, $uploaded_paths);
        $attachment_string = implode(',', $all_attachments);
        
        // Update the database
        $update_suceess = $db->query("UPDATE wp_referral_form SET attachment = '" . $attachment_string . "' WHERE id = " . $referral_id);
        
        if ($update_suceess) {
            $response['status'] = 1;
            $response['referral_id'] = base64_encode($referral_id);
            $response['total_files'] = count($all_attachments); // Send back the total count
        } else {
            $response['status'] = 0;
            $response['message'] = 'Files uploaded, but database update failed.';
        }
    } else {
        $response['status'] = 0;
        $response['message'] = 'No valid files were successfully processed for upload.';
    }

} else {
    $response['status'] = 0;
    $response['message'] = 'Invalid request or no files provided.';
}

echo json_encode($response);
die;
?>