<?php
session_start();
require_once __DIR__ . '/db/config.php';
require_once 'includes/auth_helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

if (!isset($_SESSION['user'])) {
    http_response_code(403);
    exit('Unauthorized');
}

$pdo = db();

try {
    $pdo->beginTransaction();

    // 1. Insert into customer_applications
    $stmt = $pdo->prepare(
        'INSERT INTO customer_applications (
            application_id, customer_id, created_by, company_name, company_phone, fax, gst_reg_no,
            company_reg_no, date_of_incorporation, country_of_incorporation, nature_of_business,
            credit_terms_requested, credit_limit_requested, account_setup_ar_statement,
            account_setup_dunning_letter, account_setup_ap_payment,
            declaration_name, declaration_designation, declaration_date
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
    );
    $stmt->execute([
        uniqid(),
        $_SESSION['user']['id'],
        $_SESSION['user']['id'],
        $_POST['company_name'] ?? null,
        $_POST['company_phone'] ?? null,
        $_POST['fax'] ?? null,
        $_POST['gst_reg_no'] ?? null,
        $_POST['company_reg_no'] ?? null,
        $_POST['date_of_incorporation'] ?? null,
        $_POST['country_of_incorporation'] ?? null,
        $_POST['nature_of_business'] ?? null,
        $_POST['credit_terms_requested'] ?? null,
        $_POST['credit_limit_requested'] ?? null,
        isset($_POST['account_setup_ar_statement']) ? 1 : 0,
        isset($_POST['account_setup_dunning_letter']) ? 1 : 0,
        isset($_POST['account_setup_ap_payment']) ? 1 : 0,
        $_POST['declaration_name'] ?? null,
        $_POST['declaration_designation'] ?? null,
        $_POST['declaration_date'] ?? null
    ]);
    $customer_application_id = $pdo->lastInsertId();

    // Insert Primary Contact
    if (!empty($_POST['contact_person_name']) && !empty($_POST['contact_person_email'])) {
        $stmt_contact = $pdo->prepare(
            'INSERT INTO customer_contacts (customer_application_id, name, email, phone, is_primary) VALUES (?, ?, ?, ?, ?)'
        );
        $stmt_contact->execute([
            $customer_application_id,
            $_POST['contact_person_name'],
            $_POST['contact_person_email'],
            $_POST['contact_person_phone'] ?? null,
            1 // Set as primary contact
        ]);
    }

    // Insert Billing Address
    if (!empty($_POST['company_address'])) {
        $stmt_address = $pdo->prepare(
            'INSERT INTO customer_addresses (customer_application_id, address_type, address_line_1) VALUES (?, ?, ?)'
        );
        $stmt_address->execute([$customer_application_id, 'BILLING', $_POST['company_address']]);
    }

    // Insert Delivery Address
    if (!empty($_POST['del_to_address'])) {
        $stmt_del_address = $pdo->prepare(
            'INSERT INTO customer_addresses (customer_application_id, address_type, address_line_1) VALUES (?, ?, ?)'
        );
        $stmt_del_address->execute([$customer_application_id, 'SHIPPING', $_POST['del_to_address']]);
    }

    // 2. Insert into shareholder_director_information
    if (isset($_POST['shareholder']) && is_array($_POST['shareholder'])) {
        $stmt_shareholder = $pdo->prepare(
            'INSERT INTO shareholder_director_information (application_id, name, address, nric_fin, perc_of_shareholding, contact_no) VALUES (?, ?, ?, ?, ?, ?)'
        );
        foreach ($_POST['shareholder'] as $shareholder) {
            if (empty($shareholder['name'])) continue; // Skip empty rows
            $stmt_shareholder->execute([
                $customer_application_id,
                $shareholder['name'] ?? null,
                $shareholder['address'] ?? null,
                $shareholder['nric_fin'] ?? null,
                $shareholder['perc_of_shareholding'] ?? null,
                $shareholder['contact_no'] ?? null
            ]);
        }
    }

    // 3. Insert into customer_trade_references
    if (isset($_POST['trade_reference']) && is_array($_POST['trade_reference'])) {
        $stmt_trade_ref = $pdo->prepare(
            'INSERT INTO customer_trade_references (customer_application_id, company_name, contact_person, telephone_no, fax_no) VALUES (?, ?, ?, ?, ?)'
        );
        foreach ($_POST['trade_reference'] as $trade_ref) {
            if (empty($trade_ref['company_name'])) continue; // Skip empty rows
            $stmt_trade_ref->execute([
                $customer_application_id,
                $trade_ref['company_name'] ?? null,
                $trade_ref['contact_person'] ?? null,
                $trade_ref['telephone_no'] ?? null,
                $trade_ref['fax_no'] ?? null
            ]);
        }
    }

    // 4. Insert into customer_bank_details
    if (!empty($_POST['bank_name'])) {
        $stmt_bank = $pdo->prepare(
            'INSERT INTO customer_bank_details (customer_application_id, bank_name, address, swift_code, account_number, contact_person, telephone_no, fax_no) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
        );
        $stmt_bank->execute([
            $customer_application_id,
            $_POST['bank_name'] ?? null,
            $_POST['bank_address'] ?? null,
            $_POST['bank_swift_code'] ?? null,
            $_POST['bank_account_no'] ?? null,
            $_POST['bank_contact_person'] ?? null,
            $_POST['bank_telephone_no'] ?? null,
            $_POST['bank_fax_no'] ?? null
        ]);
    }

    // 5. Insert into customer_financial_information
     if (!empty($_POST['paid_up_capital'])) {
        $stmt_financial = $pdo->prepare(
            'INSERT INTO customer_financial_information (customer_application_id, latest_audited_financial_year, shareholder_equity, paid_up_capital, annual_turnover, net_profit_loss, currency) VALUES (?, ?, ?, ?, ?, ?, ?)'
        );
        $stmt_financial->execute([
            $customer_application_id,
            $_POST['latest_audited_financial_year'] ?? null,
            $_POST['shareholder_equity'] ?? null,
            $_POST['paid_up_capital'] ?? null,
            $_POST['annual_turnover'] ?? null,
            $_POST['net_profit_loss'] ?? null,
            $_POST['currency'] ?? null
        ]);
    }

    // Set initial approval status
    $stmt_role = $pdo->prepare("SELECT id FROM roles WHERE name = 'Sales Manager'");
    $stmt_role->execute();
    $approver_role = $stmt_role->fetch(PDO::FETCH_ASSOC);
    $approver_role_id = $approver_role ? $approver_role['id'] : null;

    $stmt_update = $pdo->prepare('UPDATE customer_applications SET approval_level = 1, current_approver_role_id = ? WHERE id = ?');
    $stmt_update->execute([$approver_role_id, $customer_application_id]);

    $pdo->commit();

    $_SESSION['flash_message'] = [
        'type' => 'success',
        'message' => 'Customer application submitted successfully!'
    ];
    header('Location: index.php');
    exit();

} catch (PDOException $e) {
    $pdo->rollBack();
    error_log('Application submission failed: ' . $e->getMessage());
    
    $_SESSION['flash_message'] = [
        'type' => 'danger',
        'message' => 'There was an error submitting your application. Please check the data and try again. Error: ' . $e->getMessage()
    ];
    header('Location: new_application.php');
    exit();
}
