<?php
require_once dirname(__DIR__, 2) . '/includes/db.php';

if (ob_get_length()) ob_clean(); 
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    try {
        $supplier_type = $_POST['supplier_type'] ?? 'Company';
        
        $company_name = trim($conn->real_escape_string($_POST['company_name'] ?? ''));
        $first_name   = trim($conn->real_escape_string($_POST['first_name'] ?? ''));
        $middle_name  = trim($conn->real_escape_string($_POST['middle_name'] ?? ''));
        $last_name    = trim($conn->real_escape_string($_POST['last_name'] ?? ''));
        
        $reg_num      = trim($conn->real_escape_string($_POST['registration_number'] ?? ''));
        $tin_num      = trim($conn->real_escape_string($_POST['tin_number'] ?? ''));
        $nid_type_id  = !empty($_POST['national_id_type_id']) ? (int)$_POST['national_id_type_id'] : null;
        $nid_num      = trim($conn->real_escape_string($_POST['national_id_number'] ?? ''));
        
        $contact_p    = trim($conn->real_escape_string($_POST['contact_person'] ?? ''));
        $mobile       = trim($conn->real_escape_string($_POST['mobile'] ?? ''));
        $email        = trim($conn->real_escape_string($_POST['email'] ?? ''));
        $region_id    = !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null;
        $city         = trim($conn->real_escape_string($_POST['city'] ?? ''));
        $gps          = trim($conn->real_escape_string($_POST['digital_address'] ?? ''));

        // Dynamic Integrity Validation
        if ($supplier_type === 'Company' && empty($company_name)) {
            throw new Exception("Organization Name is mandatory for company entities.");
        }
        if ($supplier_type === 'Individual' && (empty($first_name) || empty($last_name))) {
            throw new Exception("First and Last Name are mandatory for individual proprietors.");
        }
        if (empty($mobile)) throw new Exception("A primary mobile contact is required.");

        // Insert Master Record (using national_id_type_id)
        $stmt = $conn->prepare("
            INSERT INTO suppliers 
            (supplier_type, company_name, first_name, middle_name, last_name, registration_number, tin_number, national_id_type_id, national_id_number, contact_person, mobile, email, region_id, city, digital_address, is_active) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
        ");
        
        // Parameter structure: 7 strings, 1 int, 4 strings, 1 int, 2 strings = 15 total (sssssssisssisss)
        $stmt->bind_param("sssssssisssisss", $supplier_type, $company_name, $first_name, $middle_name, $last_name, $reg_num, $tin_num, $nid_type_id, $nid_num, $contact_p, $mobile, $email, $region_id, $city, $gps);
        if (!$stmt->execute()) throw new Exception("Database Insert Error: " . $stmt->error);
        
        $new_supplier_id = $conn->insert_id;
        $stmt->close();

        // Auto-Generate and Update Supplier Code (e.g., SUP-0024)
        $sup_code = "SUP-" . str_pad($new_supplier_id, 4, '0', STR_PAD_LEFT);
        $conn->query("UPDATE suppliers SET supplier_code = '{$sup_code}' WHERE id = {$new_supplier_id}");

        // Multi-Mapping Role Integrity (Categories)
        if (!empty($_POST['categories']) && is_array($_POST['categories'])) {
            $stmtRole = $conn->prepare("INSERT INTO supplier_category_mapping (supplier_id, category_id) VALUES (?, ?)");
            foreach ($_POST['categories'] as $cat_id) {
                $c_id = (int)$cat_id;
                $stmtRole->bind_param("ii", $new_supplier_id, $c_id);
                $stmtRole->execute();
            }
            $stmtRole->close();
        }

        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => "Business Partner successfully registered with ID: <strong>{$sup_code}</strong>"]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}
?>