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

redirect_if_not_authenticated();

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: view_applications.php');
    exit();
}

$application_id = $_GET['id'];
$pdo = db();

// Fetch application details
$stmt = $pdo->prepare('SELECT * FROM customer_applications WHERE id = ?');
$stmt->execute([$application_id]);
$application = $stmt->fetch();

if (!$application) {
    die('Application not found.');
}

// Fetch contacts
$stmt = $pdo->prepare('SELECT * FROM customer_contacts WHERE customer_application_id = ?');
$stmt->execute([$application_id]);
$contacts = $stmt->fetchAll();

// Fetch addresses
$stmt = $pdo->prepare('SELECT * FROM customer_addresses WHERE customer_application_id = ?');
$stmt->execute([$application_id]);
$addresses = $stmt->fetchAll();

// Fetch trade references
$stmt = $pdo->prepare('SELECT * FROM customer_trade_references WHERE customer_application_id = ?');
$stmt->execute([$application_id]);
$trade_references = $stmt->fetchAll();

// Fetch bank details
$stmt = $pdo->prepare('SELECT * FROM customer_bank_details WHERE customer_application_id = ?');
$stmt->execute([$application_id]);
$bank_details = $stmt->fetch();

// Fetch principals
$stmt = $pdo->prepare('SELECT * FROM customer_principals WHERE customer_application_id = ?');
$stmt->execute([$application_id]);
$principals = $stmt->fetchAll();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Application - <?= htmlspecialchars($application['application_id']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">Customer Master</a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">Dashboard</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="view_applications.php">View Applications</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="logout.php">Logout</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="container mt-4">
        <h2>Application Details: <?= htmlspecialchars($application['application_id']) ?></h2>

        <!-- Company Details -->
        <div class="card mb-4">
            <div class="card-header">Company Details</div>
            <div class="card-body">
                <p><strong>Company Name:</strong> <?= htmlspecialchars($application['company_name']) ?></p>
                <p><strong>Company Website:</strong> <a href="<?= htmlspecialchars($application['company_website']) ?>" target="_blank"><?= htmlspecialchars($application['company_website']) ?></a></p>
                <p><strong>Company Phone:</strong> <?= htmlspecialchars($application['company_phone']) ?></p>
                <p><strong>Sales Owner:</strong> <?= htmlspecialchars($application['sales_owner']) ?></p>
                <p><strong>Payment Terms:</strong> <?= htmlspecialchars($application['payment_terms']) ?></p>
                <p><strong>Tags:</strong> <?= htmlspecialchars($application['tags']) ?></p>
                <p><strong>Notes:</strong> <?= nl2br(htmlspecialchars($application['notes'])) ?></p>
            </div>
        </div>

        <!-- Financial & Credit Details -->
        <div class="card mb-4">
            <div class="card-header">Financial & Credit Details</div>
            <div class="card-body">
                <p><strong>Major Product:</strong> <?= htmlspecialchars($application['major_product']) ?></p>
                <p><strong>Capital:</strong> <?= htmlspecialchars($application['capital']) ?> <?= htmlspecialchars($application['capital_currency']) ?></p>
                <p><strong>Main Shareholders:</strong> <?= htmlspecialchars($application['main_shareholders']) ?></p>
                <p><strong>Number of Employees:</strong> <?= htmlspecialchars($application['num_employees']) ?></p>
                <p><strong>Payment Terms AR:</strong> <?= htmlspecialchars($application['payment_terms_ar']) ?></p>
                <hr>
                <h6>P/L Information</h6>
                <p><strong>Year:</strong> <?= htmlspecialchars($application['pl_year']) ?></p>
                <p><strong>Net Sales:</strong> <?= htmlspecialchars($application['net_sales']) ?></p>
                <p><strong>Net Income Margin:</strong> <?= htmlspecialchars($application['net_income_margin']) ?></p>
                <p><strong>Net Income Margin Ratio:</strong> <?= htmlspecialchars($application['net_income_margin_ratio']) ?>%</p>
                <hr>
                 <h6>ROHM Sales Target (KUS$)</h6>
                <p><strong>This Year:</strong> <?= htmlspecialchars($application['sales_target_this_year']) ?></p>
                <p><strong>Next Year:</strong> <?= htmlspecialchars($application['sales_target_next_year']) ?></p>
                <p><strong>After the Next:</strong> <?= htmlspecialchars($application['sales_target_after_next']) ?></p>
                <hr>
                <h6>Credit Information</h6>
                <p><strong>Rank:</strong> <?= htmlspecialchars($application['credit_rank']) ?></p>
                <p><strong>Limit:</strong> <?= htmlspecialchars($application['credit_limit']) ?> KUS$</p>
                <hr>
                <h6>Credit Research</h6>
                <p><strong>Status:</strong> <?= htmlspecialchars($application['credit_research_status']) ?></p>
                <p><strong>Reason:</strong> <?= htmlspecialchars($application['credit_research_reason']) ?></p>
                <hr>
                <p><strong>Tax Rate/Area (GST TYPE):</strong> <?= htmlspecialchars($application['tax_rate_area']) ?></p>
                <p><strong>Billing Type:</strong> <?= htmlspecialchars($application['billing_type']) ?></p>
            </div>
        </div>

        <!-- Del-To Informations -->
        <div class="card mb-4">
            <div class="card-header">Del-To Informations</div>
            <div class="card-body">
                <p><strong>Del-To Code:</strong> <?= htmlspecialchars($application['del_to_code']) ?></p>
                <p><strong>Abbreviation of Delivery-To:</strong> <?= htmlspecialchars($application['delivery_abbreviation']) ?></p>
                <p><strong>Customer Name:</strong> <?= htmlspecialchars($application['del_to_customer_name']) ?></p>
                <p><strong>Address:</strong><br>
                    <?= htmlspecialchars($application['del_to_address_1']) ?><br>
                    <?php if(!empty($application['del_to_address_2'])): ?>
                        <?= htmlspecialchars($application['del_to_address_2']) ?><br>
                    <?php endif; ?>
                    <?php if(!empty($application['del_to_address_3'])): ?>
                        <?= htmlspecialchars($application['del_to_address_3']) ?><br>
                    <?php endif; ?>
                    <?php if(!empty($application['del_to_address_4'])): ?>
                        <?= htmlspecialchars($application['del_to_address_4']) ?><br>
                    <?php endif; ?>
                </p>
                <p><strong>Postcode (Zip Code):</strong> <?= htmlspecialchars($application['del_to_postcode']) ?></p>
                <p><strong>Phone Number:</strong> <?= htmlspecialchars($application['del_to_phone']) ?></p>
                <p><strong>Area Code:</strong> <?= htmlspecialchars($application['del_to_area_code']) ?></p>
                <p><strong>Transportation Code:</strong> <?= htmlspecialchars($application['del_to_transportation_code']) ?></p>
                <p><strong>Stock Point Code:</strong> <?= htmlspecialchars($application['del_to_stock_point_code']) ?></p>
                <p><strong>Recipient Section:</strong> <?= htmlspecialchars($application['del_to_recipient_section']) ?></p>
                <p><strong>Country Code:</strong> <?= htmlspecialchars($application['del_to_country_code']) ?></p>
                <p><strong>Shipment Flag:</strong> <?= htmlspecialchars($application['del_to_shipment_flag']) ?></p>
                <p><strong>Number of Date for Transport:</strong> <?= htmlspecialchars($application['del_to_transport_days']) ?></p>
                <p><strong>Shipment Condition: Category:</strong> <?= htmlspecialchars($application['del_to_shipment_condition_category']) ?></p>
                <p><strong>Transport Service Exist:</strong> <?= htmlspecialchars($application['del_to_transport_service_exist']) ?></p>
                <p><strong>Shipment Condition: Place:</strong> <?= htmlspecialchars($application['del_to_shipment_condition_place']) ?></p>
            </div>
        </div>

        <!-- SOP -->
        <div class="card mb-4">
            <div class="card-header">SOP</div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h5>Document Requirements</h5>
                        <p><strong>D/O*:</strong> <?= htmlspecialchars($application['doc_req_do']) ?></p>
                        <p><strong>Packing List*:</strong> <?= htmlspecialchars($application['doc_req_packing_list']) ?></p>
                        <p><strong>Invoice*:</strong> <?= htmlspecialchars($application['doc_req_invoice']) ?></p>
                        <p><strong>Export Permit:</strong> <?= htmlspecialchars($application['doc_req_export_permit']) ?></p>
                        <p><strong>1 PO/1 DO/1 INV:</strong> <?= htmlspecialchars($application['doc_req_po_do_inv']) ?></p>
                        <p><strong>1 DO/1 INV:</strong> <?= htmlspecialchars($application['doc_req_do_inv']) ?></p>
                        <p><strong>Others:</strong> <?= nl2br(htmlspecialchars($application['doc_req_others'])) ?></p>
                    </div>
                    <div class="col-md-6">
                        <h5>Packing Requirements</h5>
                        <p><strong>One Line One Carton:</strong> <?= htmlspecialchars($application['pack_req_one_line_carton']) ?></p>
                        <p><strong>One Item One Carton:</strong> <?= htmlspecialchars($application['pack_req_one_item_carton']) ?></p>
                        <p><strong>One Item One Pocket:</strong> <?= htmlspecialchars($application['pack_req_one_item_pocket']) ?></p>
                        <p><strong>Special Thomson Label:</strong> <?= htmlspecialchars($application['pack_req_thomson_label']) ?></p>
                        <p><strong>Special Contents Label:</strong> <?= htmlspecialchars($application['pack_req_contents_label']) ?></p>
                        <p><strong>Delivery schedule:</strong> <?= htmlspecialchars($application['pack_req_delivery_schedule']) ?></p>
                    </div>
                </div>
                <hr>
                <h5>Forwarder Information</h5>
                <p><strong>Forwarder Name:</strong> <?= htmlspecialchars($application['forwarder_name']) ?></p>
                <p><strong>Forwarder Code:</strong> <?= htmlspecialchars($application['forwarder_code']) ?></p>
                <p><strong>Forwarder Address:</strong> <?= nl2br(htmlspecialchars($application['forwarder_address'])) ?></p>
                <p><strong>Contact Person:</strong> <?= htmlspecialchars($application['forwarder_contact_person']) ?></p>
                <p><strong>Phone:</strong> <?= htmlspecialchars($application['forwarder_phone']) ?></p>
                <p><strong>Fax:</strong> <?= htmlspecialchars($application['forwarder_fax']) ?></p>
                <p><strong>Delivery Method:</strong> <?= htmlspecialchars($application['forwarder_delivery_method']) ?></p>
                <p><strong>Delivery Timings:</strong> <?= htmlspecialchars($application['forwarder_delivery_timings']) ?></p>
                <p><strong>Delivery Requirements:</strong> <?= nl2br(htmlspecialchars($application['forwarder_delivery_requirements'])) ?></p>
                <hr>
                <h5>Special Instructions</h5>
                <p><strong>Shipping Mark:</strong> <?= htmlspecialchars($application['special_instructions_shipping_mark']) ?></p>
                <p><strong>Fax Documents:</strong> <?= htmlspecialchars($application['special_instructions_fax_documents']) ?></p>
                <p><strong>Details:</strong> <?= htmlspecialchars($application['special_instructions_details']) ?></p>
                <p><strong>Attention To:</strong> <?= htmlspecialchars($application['special_instructions_attention_to']) ?></p>
                <p><strong>Fax Number:</strong> <?= htmlspecialchars($application['special_instructions_fax_number']) ?></p>
                <p><strong>Remarks:</strong> <?= nl2br(htmlspecialchars($application['remarks'])) ?></p>
            </div>
        </div>

        <!-- Contacts -->
        <div class="card mb-4">
            <div class="card-header">Contacts</div>
            <div class="card-body">
                <?php foreach ($contacts as $contact): ?>
                    <div class="mb-3 border-bottom pb-3">
                        <p><strong>Name:</strong> <?= htmlspecialchars($contact['name']) ?> <?= $contact['is_primary'] ? '(Primary)' : '' ?></p>
                        <p><strong>Email:</strong> <?= htmlspecialchars($contact['email']) ?></p>
                        <p><strong>Phone:</strong> <?= htmlspecialchars($contact['phone']) ?></p>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Addresses -->
        <div class="card mb-4">
            <div class="card-header">Addresses</div>
            <div class="card-body">
                <?php foreach ($addresses as $address): ?>
                    <div class="mb-3 border-bottom pb-3">
                        <p><strong>Type:</strong> <?= htmlspecialchars($address['address_type']) ?></p>
                        <p><strong>Address:</strong><br>
                            <?= htmlspecialchars($address['address_line_1']) ?><br>
                            <?php if(!empty($address['address_line_2'])): ?>
                                <?= htmlspecialchars($address['address_line_2']) ?><br>
                            <?php endif; ?>
                            <?= htmlspecialchars($address['city']) ?>, <?= htmlspecialchars($address['state']) ?> <?= htmlspecialchars($address['postal_code']) ?><br>
                            <?= htmlspecialchars($address['country']) ?>
                        </p>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Trade References -->
        <div class="card mb-4">
            <div class="card-header">Trade References</div>
            <div class="card-body">
                <?php foreach ($trade_references as $ref): ?>
                    <div class="mb-3 border-bottom pb-3">
                        <p><strong>Company Name:</strong> <?= htmlspecialchars($ref['company_name']) ?></p>
                        <p><strong>Contact Person:</strong> <?= htmlspecialchars($ref['contact_person']) ?></p>
                        <p><strong>Email:</strong> <?= htmlspecialchars($ref['email']) ?></p>
                        <p><strong>Phone:</strong> <?= htmlspecialchars($ref['phone']) ?></p>
                        <p><strong>Address:</strong> <?= htmlspecialchars($ref['address']) ?></p>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Bank Details -->
        <div class="card mb-4">
            <div class="card-header">Bank Details</div>
            <div class="card-body">
                <p><strong>Bank Name:</strong> <?= htmlspecialchars($bank_details['bank_name']) ?></p>
                <p><strong>Branch:</strong> <?= htmlspecialchars($bank_details['branch']) ?></p>
                <p><strong>BSB Number:</strong> <?= htmlspecialchars($bank_details['bsb_number']) ?></p>
                <p><strong>Account Number:</strong> <?= htmlspecialchars($bank_details['account_number']) ?></p>
                <p><strong>Account Name:</strong> <?= htmlspecialchars($bank_details['account_name']) ?></p>
            </div>
        </div>

        <!-- Declaration and Signature -->
        <div class="card mb-4">
            <div class="card-header">Declaration and Signature</div>
            <div class="card-body">
                <p><strong>Declaration:</strong> <?= nl2br(htmlspecialchars($application['declaration_text'])) ?></p>
                <?php if (!empty($application['signature_path'])): ?>
                    <p><strong>Signature:</strong></p>
                    <img src="<?= htmlspecialchars($application['signature_path']) ?>" alt="Signature" class="img-fluid">
                <?php else: ?>
                    <p>No signature provided.</p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Application Summary -->
        <div class="card mb-4">
            <div class="card-header">Application Summary</div>
            <div class="card-body">
                <h5>Company Details</h5>
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>Customer Name:</strong> <?= htmlspecialchars($application['company_name']) ?></p>
                        <p><strong>Major Product of Customer:</strong> <?= htmlspecialchars($application['major_product']) ?></p>
                        <p><strong>Capital:</strong> <?= htmlspecialchars($application['capital']) ?> <?= htmlspecialchars($application['capital_currency']) ?></p>
                        <p><strong>Main Shareholders:</strong> <?= htmlspecialchars($application['main_shareholders']) ?></p>
                        <p><strong>Number of Employee:</strong> <?= htmlspecialchars($application['num_employees']) ?></p>
                        <p><strong>Payment Terms AR:</strong> <?= htmlspecialchars($application['payment_terms_ar']) ?></p>
                    </div>
                    <div class="col-md-6">
                        <h6>Customer's P/L Information</h6>
                        <p><strong>Year:</strong> <?= htmlspecialchars($application['pl_year']) ?></p>
                        <p><strong>Net Sales:</strong> <?= htmlspecialchars($application['net_sales']) ?></p>
                        <p><strong>Net Income Margin:</strong> <?= htmlspecialchars($application['net_income_margin']) ?></p>
                        <p><strong>Net Income Margin Ratio(%):</strong> <?= htmlspecialchars($application['net_income_margin_ratio']) ?></p>
                    </div>
                </div>
                <hr>
                <div class="row">
                    <div class="col-md-6">
                        <h6>ROHM Sales Target</h6>
                        <p><strong>This Year:</strong> <?= htmlspecialchars($application['sales_target_this_year']) ?> KUS$</p>
                        <p><strong>Next Year:</strong> <?= htmlspecialchars($application['sales_target_next_year']) ?> KUS$</p>
                        <p><strong>After the Next:</strong> <?= htmlspecialchars($application['sales_target_after_next']) ?> KUS$</p>
                    </div>
                    <div class="col-md-6">
                        <h6>Credit Information</h6>
                        <p><strong>Rank:</strong> <?= htmlspecialchars($application['credit_rank']) ?></p>
                        <p><strong>Limit (KUS$):</strong> <?= htmlspecialchars($application['credit_limit']) ?></p>
                    </div>
                </div>
                <hr>
                <div class="row">
                    <div class="col-md-6">
                        <h6>Credit Research</h6>
                        <p><strong>Status:</strong> <?= htmlspecialchars($application['credit_research_status']) ?></p>
                        <p><strong>Reason:</strong> <?= htmlspecialchars($application['credit_research_reason']) ?></p>
                    </div>
                    <div class="col-md-6">
                        <h6>Other Details</h6>
                        <p><strong>Tax Rate/Area (GST TYPE):</strong> <?= htmlspecialchars($application['tax_rate_area']) ?></p>
                        <p><strong>Billing Type:</strong> <?= htmlspecialchars($application['billing_type']) ?></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">Principals Summary</div>
            <div class="card-body">
                <?php foreach ($principals as $principal): ?>
                    <div class="mb-3 border-bottom pb-3">
                        <p><strong>Name:</strong> <?= htmlspecialchars($principal['name']) ?></p>
                        <p><strong>Title:</strong> <?= htmlspecialchars($principal['title']) ?></p>
                        <p><strong>Ownership %:</strong> <?= htmlspecialchars($principal['ownership_percentage']) ?></p>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">Contacts Summary</div>
            <div class="card-body">
                <?php foreach ($contacts as $contact): ?>
                    <div class="mb-3 border-bottom pb-3">
                        <p><strong>Name:</strong> <?= htmlspecialchars($contact['name']) ?> <?= $contact['is_primary'] ? '(Primary)' : '' ?></p>
                        <p><strong>Email:</strong> <?= htmlspecialchars($contact['email']) ?></p>
                        <p><strong>Phone:</strong> <?= htmlspecialchars($contact['phone']) ?></p>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">Trade References Summary</div>
            <div class="card-body">
                <?php foreach ($trade_references as $ref): ?>
                    <div class="mb-3 border-bottom pb-3">
                        <p><strong>Company Name:</strong> <?= htmlspecialchars($ref['company_name']) ?></p>
                        <p><strong>Contact Person:</strong> <?= htmlspecialchars($ref['contact_person']) ?></p>
                        <p><strong>Email:</strong> <?= htmlspecialchars($ref['email']) ?></p>
                        <p><strong>Phone:</strong> <?= htmlspecialchars($ref['phone']) ?></p>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">Bank Reference Summary</div>
            <div class="card-body">
                <p><strong>Bank Name:</strong> <?= htmlspecialchars($bank_details['bank_name']) ?></p>
                <p><strong>Branch:</strong> <?= htmlspecialchars($bank_details['branch']) ?></p>
                <p><strong>Account Number:</strong> <?= htmlspecialchars($bank_details['account_number']) ?></p>
                <p><strong>Account Name:</strong> <?= htmlspecialchars($bank_details['account_name']) ?></p>
            </div>
        </div>

        <!-- Approval Section -->
        <?php 
        $approval_level = $application['approval_level'];
        $permission_needed = 'approve_level_' . $approval_level;
        if (hasPermission($permission_needed) && $application['status'] === 'PENDING_APPROVAL'): 
        ?>
        <div class="card mb-4">
            <div class="card-header">Approval Action</div>
            <div class="card-body">
                <form action="process_approval.php" method="POST">
                    <input type="hidden" name="application_id" value="<?= $application['id'] ?>">
                    <button type="submit" name="action" value="approve" class="btn btn-success">Approve</button>
                    <button type="submit" name="action" value="reject" class="btn btn-danger">Reject</button>
                </form>
            </div>
        </div>
        <?php endif; ?>

    </div>
</body>
</html>