<?php
session_start();
require_once __DIR__ . '/db/config.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 {
    // Get the role ID for the first approval level
    $stmt_role = $pdo->prepare("SELECT id FROM roles WHERE name = 'Approver Level 1'");
    $stmt_role->execute();
    $approver_role = $stmt_role->fetch(PDO::FETCH_ASSOC);
    $approver_role_id = $approver_role ? $approver_role['id'] : null;

    $pdo->beginTransaction();

    // 1. Insert into customer_applications
    $application_id = 'APP-' . strtoupper(uniqid());
    $created_by = $_SESSION['user']['username'] ?? 'system';

    $stmt = $pdo->prepare(
        'INSERT INTO customer_applications (user_id, company_name, company_website, company_phone, sales_owner, payment_terms, tags, notes, declaration_text, signature_path, major_product, capital, capital_currency, main_shareholders, num_employees, payment_terms_ar, pl_year, net_sales, net_income_margin, net_income_margin_ratio, sales_target_this_year, sales_target_next_year, sales_target_after_next, credit_rank, credit_limit, credit_research_status, credit_research_reason, tax_rate_area, billing_type, del_to_code, delivery_abbreviation, del_to_customer_name, del_to_address_1, del_to_address_2, del_to_address_3, del_to_address_4, del_to_postcode, del_to_phone, del_to_area_code, del_to_transportation_code, del_to_stock_point_code, del_to_recipient_section, del_to_country_code, del_to_shipment_flag, del_to_transport_days, del_to_shipment_condition_category, del_to_transport_service_exist, del_to_shipment_condition_place, doc_req_do, doc_req_packing_list, doc_req_invoice, doc_req_export_permit, doc_req_po_do_inv, doc_req_do_inv, doc_req_others, pack_req_one_line_carton, pack_req_one_item_carton, pack_req_one_item_pocket, pack_req_thomson_label, pack_req_contents_label, pack_req_delivery_schedule, forwarder_name, forwarder_code, forwarder_address, forwarder_contact_person, forwarder_phone, forwarder_fax, forwarder_delivery_method, forwarder_delivery_timings, forwarder_delivery_requirements, special_instructions_shipping_mark, special_instructions_fax_documents, special_instructions_details, special_instructions_attention_to, special_instructions_fax_number, remarks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
    );
    $stmt->execute([
        $_SESSION['user_id'],
        $_POST['company_name'],
        $_POST['company_website'],
        $_POST['company_phone'],
        $_POST['sales_owner'],
        $_POST['payment_terms'],
        $_POST['tags'],
        $_POST['notes'],
        $_POST['declaration_text'],
        $signature_path,
        $_POST['major_product'] ?? null,
        $_POST['capital'] ?? null,
        $_POST['capital_currency'] ?? null,
        $_POST['main_shareholders'] ?? null,
        $_POST['num_employees'] ?? null,
        $_POST['payment_terms_ar'] ?? null,
        $_POST['pl_year'] ?? null,
        $_POST['net_sales'] ?? null,
        $_POST['net_income_margin'] ?? null,
        $_POST['net_income_margin_ratio'] ?? null,
        $_POST['sales_target_this_year'] ?? null,
        $_POST['sales_target_next_year'] ?? null,
        $_POST['sales_target_after_next'] ?? null,
        $_POST['credit_rank'] ?? null,
        $_POST['credit_limit'] ?? null,
        $_POST['credit_research_status'] ?? null,
        $_POST['credit_research_reason'] ?? null,
        $_POST['tax_rate_area'] ?? null,
        $_POST['billing_type'] ?? null,
        $_POST['del_to_code'] ?? null,
        $_POST['delivery_abbreviation'] ?? null,
        $_POST['del_to_customer_name'] ?? null,
        $_POST['del_to_address_1'] ?? null,
        $_POST['del_to_address_2'] ?? null,
        $_POST['del_to_address_3'] ?? null,
        $_POST['del_to_address_4'] ?? null,
        $_POST['del_to_postcode'] ?? null,
        $_POST['del_to_phone'] ?? null,
        $_POST['del_to_area_code'] ?? null,
        $_POST['del_to_transportation_code'] ?? null,
        $_POST['del_to_stock_point_code'] ?? null,
        $_POST['del_to_recipient_section'] ?? null,
        $_POST['del_to_country_code'] ?? null,
        $_POST['del_to_shipment_flag'] ?? null,
        $_POST['del_to_transport_days'] ?? null,
        $_POST['del_to_shipment_condition_category'] ?? null,
        isset($_POST['del_to_transport_service_exist']) ? implode(',', $_POST['del_to_transport_service_exist']) : null,
        $_POST['del_to_shipment_condition_place'] ?? null,
        $_POST['doc_req_do'] ?? null,
        $_POST['doc_req_packing_list'] ?? null,
        $_POST['doc_req_invoice'] ?? null,
        $_POST['doc_req_export_permit'] ?? null,
        $_POST['doc_req_po_do_inv'] ?? null,
        $_POST['doc_req_do_inv'] ?? null,
        $_POST['doc_req_others'] ?? null,
        $_POST['pack_req_one_line_carton'] ?? null,
        $_POST['pack_req_one_item_carton'] ?? null,
        $_POST['pack_req_one_item_pocket'] ?? null,
        $_POST['pack_req_thomson_label'] ?? null,
        $_POST['pack_req_contents_label'] ?? null,
        $_POST['pack_req_delivery_schedule'] ?? null,
        $_POST['forwarder_name'] ?? null,
        $_POST['forwarder_code'] ?? null,
        $_POST['forwarder_address'] ?? null,
        $_POST['forwarder_contact_person'] ?? null,
        $_POST['forwarder_phone'] ?? null,
        $_POST['forwarder_fax'] ?? null,
        $_POST['forwarder_delivery_method'] ?? null,
        $_POST['forwarder_delivery_timings'] ?? null,
        $_POST['forwarder_delivery_requirements'] ?? null,
        $_POST['special_instructions_shipping_mark'] ?? null,
        $_POST['special_instructions_fax_documents'] ?? null,
        $_POST['special_instructions_details'] ?? null,
        $_POST['special_instructions_attention_to'] ?? null,
        $_POST['special_instructions_fax_number'] ?? null,
        $_POST['remarks'] ?? null
    ]);
    $customer_application_id = $pdo->lastInsertId();

    // 2. Insert into customer_contacts
    if (isset($_POST['contact']) && is_array($_POST['contact'])) {
        $stmt_contact = $pdo->prepare(
            'INSERT INTO customer_contacts (customer_application_id, name, email, phone, is_primary) VALUES (?, ?, ?, ?, ?)'
        );
        foreach ($_POST['contact'] as $index => $contact) {
            $is_primary = (isset($contact['is_primary']) && $contact['is_primary'] == '1');
            $stmt_contact->execute([
                $customer_application_id,
                $contact['name'],
                $contact['email'],
                $contact['phone'],
                $is_primary ? 1 : 0
            ]);
        }
    }

    // 3. Insert into customer_addresses
    if (isset($_POST['address']) && is_array($_POST['address'])) {
        $stmt_address = $pdo->prepare(
            'INSERT INTO customer_addresses (customer_application_id, address_type, address_line_1, address_line_2, city, state, postal_code, country) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
        );
        foreach ($_POST['address'] as $address) {
            $stmt_address->execute([
                $customer_application_id,
                $address['type'],
                $address['line1'],
                $address['line2'],
                $address['city'],
                $address['state'],
                $address['postal_code'],
                $address['country']
            ]);
        }
    }

    // 4. 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, email, phone, address) VALUES (?, ?, ?, ?, ?, ?)'
        );
        foreach ($_POST['trade_reference'] as $trade_ref) {
            $stmt_trade_ref->execute([
                $customer_application_id,
                $trade_ref['company_name'],
                $trade_ref['contact_person'],
                $trade_ref['email'],
                $trade_ref['phone'],
                $trade_ref['address']
            ]);
        }
    }

    // 5. Insert into customer_bank_details
    if (isset($_POST['bank_name'])) {
        $stmt_bank = $pdo->prepare(
            'INSERT INTO customer_bank_details (customer_application_id, bank_name, branch, bsb_number, account_number, account_name) VALUES (?, ?, ?, ?, ?, ?)'
        );
        $stmt_bank->execute([
            $customer_application_id,
            $_POST['bank_name'],
            $_POST['branch'],
            $_POST['bsb_number'],
            $_POST['account_number'],
            $_POST['account_name']
        ]);
    }

    // 6. Handle Signature and Declaration
    $signature_path = null;
    if (isset($_POST['signature']) && !empty($_POST['signature'])) {
        $signature_data = $_POST['signature'];
        list($type, $data) = explode(';', $signature_data);
        list(, $data)      = explode(',', $data);
        $data = base64_decode($data);
        $signature_filename = 'signature_' . $application_id . '_' . time() . '.png';
        $signature_path = 'uploads/' . $signature_filename;
        file_put_contents($signature_path, $data);
    }

    $stmt_declar = $pdo->prepare('UPDATE customer_applications SET declaration_text = ?, signature_path = ? WHERE id = ?');
    $stmt_declar->execute([
        $_POST['declaration_text'],
        $signature_path,
        $customer_application_id
    ]);

    $pdo->commit();

    // Notify approvers
    require_once 'mail/MailService.php';
    $approver_emails = get_user_emails_by_role('Approver Level 1', $pdo);
    if (!empty($approver_emails)) {
        // Get Sales Rep name
        $stmt_sales_rep = $pdo->prepare('SELECT name FROM users WHERE id = ?');
        $stmt_sales_rep->execute([$_SESSION['user_id']]);
        $sales_rep_name = $stmt_sales_rep->fetchColumn();

        $subject = 'New Credit Application Submitted - ' . $_POST['company_name'];
        $submission_date = date('Y-m-d');
        $body = "
            <p>A new credit application has been submitted and requires your approval.</p>
            <p><strong>Customer Name:</strong> {$_POST['company_name']}</p>
            <p><strong>Sales Rep:</strong> {$sales_rep_name}</p>
            <p><strong>Credit Amount:</strong> $" . number_format($_POST['credit_limit'], 2) . "</p>
            <p><strong>Submission Date:</strong> {$submission_date}</p>
            <p><a href='http://{$_SERVER['HTTP_HOST']}/view_application.php?id={$customer_application_id}' style='display: inline-block; padding: 10px 20px; background-color: #007bff; color: #fff; text-decoration: none;'>View Application</a></p>
        ";
        MailService::sendMail($approver_emails, $subject, $body);
    }

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

function get_user_emails_by_role($role_name, $pdo) {
    $stmt = $pdo->prepare('SELECT u.email FROM users u JOIN user_roles ur ON u.id = ur.user_id JOIN roles r ON ur.role_id = r.id WHERE r.name = ?');
    $stmt->execute([$role_name]);
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

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