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

// Using your exact path
require_once __DIR__ . '/../../../dripend/includes/db.php';
try {
    // The variable $conn is defined in your db.php file
    if (!isset($conn)) {
        throw new Exception("The database connection variable '$conn' was not found in db.php.");
    }

    $db = $conn; // Map your variable to our local $db variable

    // INPUT SANITIZATION
    $data = [
        'hospital_name' => $_POST['hospital_name'] ?? 'RiMax Health Suite',
        'tax_id'        => $_POST['tax_id'] ?? '',
        'primary_phone' => $_POST['primary_phone'] ?? '',
        'sec_phone'     => $_POST['secondary_phone'] ?? '',
        'primary_email' => $_POST['primary_email'] ?? '',
        'sec_email'     => $_POST['secondary_email'] ?? '',
        'address'       => $_POST['address'] ?? '',
        'doc_align'     => $_POST['header_alignment'] ?? 'center',
        'primary_hex'   => $_POST['primary_hex'] ?? '#1E3A8A',
        'accent_hex'    => $_POST['accent_hex'] ?? '#3B82F6',
        'id_format'     => $_POST['id_format'] ?? 'FMT_B',
        'id_padding'    => $_POST['id_padding'] ?? 5,
        'opd_prefix'    => strtoupper($_POST['opd_prefix'] ?? 'RMX'),
        'enable_dual'   => isset($_POST['dual_logo_toggle']) ? 1 : 0,
        'print_photo'   => isset($_POST['print_photo']) ? 1 : 0,
        'print_blood'   => isset($_POST['print_blood']) ? 1 : 0
    ];

    // FILE UPLOAD
    $upload_dir = __DIR__ . '/../setupUploads/';
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

    $primary_logo_path = null;
    if (isset($_FILES['primary_logo']) && $_FILES['primary_logo']['error'] === UPLOAD_ERR_OK) {
        $filename = 'primary_logo_' . time() . '.' . pathinfo($_FILES['primary_logo']['name'], PATHINFO_EXTENSION);
        if (move_uploaded_file($_FILES['primary_logo']['tmp_name'], $upload_dir . $filename)) {
            $primary_logo_path = 'setupUploads/' . $filename; 
        }
    }

    $secondary_logo_path = null;
    if ($data['enable_dual'] && isset($_FILES['secondary_logo']) && $_FILES['secondary_logo']['error'] === UPLOAD_ERR_OK) {
        $filename = 'secondary_logo_' . time() . '.' . pathinfo($_FILES['secondary_logo']['name'], PATHINFO_EXTENSION);
        if (move_uploaded_file($_FILES['secondary_logo']['tmp_name'], $upload_dir . $filename)) {
            $secondary_logo_path = 'setupUploads/' . $filename;
        }
    }

    // SQL EXECUTION (Using mysqli approach since your db.php uses mysqli)
    // We escape inputs to prevent SQL Injection
    $stmt = $db->prepare("INSERT INTO facility_profile 
            (id, hospital_name, tax_id, primary_phone, secondary_phone, primary_email, secondary_email, address, enable_dual_logo, document_alignment, primary_hex, accent_hex, id_format, id_padding, opd_prefix, print_photo, print_blood_group) 
            VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 
            ON DUPLICATE KEY UPDATE 
            hospital_name=?, tax_id=?, primary_phone=?, secondary_phone=?, primary_email=?, secondary_email=?, address=?, enable_dual_logo=?, document_alignment=?, primary_hex=?, accent_hex=?, id_format=?, id_padding=?, opd_prefix=?, print_photo=?, print_blood_group=?");
    
    $stmt->bind_param("ssssssssssssssssssssssssssssssss", 
        $data['hospital_name'], $data['tax_id'], $data['primary_phone'], $data['sec_phone'], $data['primary_email'], 
        $data['sec_email'], $data['address'], $data['enable_dual'], $data['doc_align'], $data['primary_hex'], 
        $data['accent_hex'], $data['id_format'], $data['id_padding'], $data['opd_prefix'], $data['print_photo'], $data['print_blood'],
        $data['hospital_name'], $data['tax_id'], $data['primary_phone'], $data['sec_phone'], $data['primary_email'], 
        $data['sec_email'], $data['address'], $data['enable_dual'], $data['doc_align'], $data['primary_hex'], 
        $data['accent_hex'], $data['id_format'], $data['id_padding'], $data['opd_prefix'], $data['print_photo'], $data['print_blood']
    );
    
    $stmt->execute();

    if ($primary_logo_path) {
        $up = $db->prepare("UPDATE facility_profile SET primary_logo_path = ? WHERE id = 1");
        $up->bind_param("s", $primary_logo_path);
        $up->execute();
    }
    if ($secondary_logo_path) {
        $up = $db->prepare("UPDATE facility_profile SET secondary_logo_path = ? WHERE id = 1");
        $up->bind_param("s", $secondary_logo_path);
        $up->execute();
    }

    echo json_encode(['status' => 'success', 'message' => 'Facility configuration saved successfully!']);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Backend Error: ' . $e->getMessage()]);
}