<!DOCTYPE html>
<html>
<title>Delivery Note - <?= $sales_code; ?></title>
<head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel='shortcut icon' href='<?php echo $theme_link; ?>images/favicon.ico' />

<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
    font-family: 'Open Sans', 'Martel Sans', sans-serif;
}
th, td {
    padding: 5px;
    text-align: left;
    vertical-align:top
}
.no-border, .no-border td, .no-border th {
    border: none;
}
.header-table {
    border: none;
    width: 100%;
    margin-bottom: 10px;
}
.header-table td {
    border: none;
    vertical-align: top;
}
.document-title {
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    margin: 20px 0;
    text-decoration: underline;
}
@media print {
    .no-print {
        display: none !important;
    }
}
</style>
</head>
<body onload="window.print();">
<?php

    $CI =& get_instance();

    $q3=$this->db->query("SELECT b.store_id,a.customer_name,a.mobile,a.phone,a.gstin,a.tax_number,a.email,
                           a.opening_balance,a.country_id,a.state_id,a.city,
                           a.postcode,a.address,b.sales_date,b.created_time,b.reference_no,
                           b.lpo_number,b.sales_code,b.sales_note,b.sales_status,
                           coalesce(b.grand_total,0) as grand_total,
                           coalesce(b.subtotal,0) as subtotal,
                           b.payment_status

                           FROM db_customers a,
                           db_sales b
                           WHERE
                           a.`id`=b.`customer_id` AND
                           b.`id`='$sales_id' AND b.store_id=".get_current_store_id());

     if($q3->num_rows()==0){
      $CI->show_access_denied_page();
    }
    $res3=$q3->row();
    $customer_name=$res3->customer_name;
    $customer_mobile=$res3->mobile;
    $customer_phone=$res3->phone;
    $customer_email=$res3->email;
    $customer_country=$res3->country_id;
    $customer_state=$res3->state_id;
    $customer_city=$res3->city;
    $customer_address=$res3->address;
    $customer_postcode=$res3->postcode;
    $customer_gst_no=$res3->gstin;
    $customer_tax_number=$res3->tax_number;
    $sales_date=$res3->sales_date;
    $created_time=$res3->created_time;
    $reference_no=$res3->reference_no;
    $lpo_number=isset($res3->lpo_number) ? $res3->lpo_number : '';
    $sales_code=$res3->sales_code;
    $sales_note=$res3->sales_note;
    $sales_status=$res3->sales_status;
    $grand_total=$res3->grand_total;

    if(!empty($customer_country)){
      $customer_country = $this->db->query("select country from db_country where id='$customer_country'")->row()->country;
    }
    if(!empty($customer_state)){
      $customer_state = $this->db->query("select state from db_states where id='$customer_state'")->row()->state;
    }


    $q1=$this->db->query("select * from db_store where id=".get_current_store_id());
    $res1=$q1->row();
    $store_name=$res1->store_name;
    $company_mobile=$res1->mobile;
    $company_phone=$res1->phone;
    $company_email=$res1->email;
    $company_address=$res1->address;
    $company_city=$res1->city;
    $company_pincode=$res1->pincode;
    $company_website=$res1->website;
    $company_state=$res1->state_id;
    $company_gstin=$res1->gstin;
    $company_tax_number=$res1->tax_number;

    if(!empty($company_state)){
      $company_state = $this->db->query("select state from db_states where id='$company_state'")->row()->state;
    }

    $logo_path=$res1->logo_path;
    $sales_invoice_footer_text=$res1->sales_invoice_footer_text;

?>

<!-- Header with Company Info - Centered -->
<table class="header-table">
    <tr>
        <td style="text-align: center;">
            <?php if (!empty($logo_path)) { ?>
                <img src="<?= base_url() . $logo_path; ?>" alt="Company Logo" style="max-width: 150px; max-height: 80px; margin-bottom: 5px;"><br>
            <?php } ?>
            <strong style="font-size: 20px;"><?= $store_name; ?></strong><br>
            <?php if (!empty($company_address)) echo $company_address . '<br>'; ?>
            <?php
            $location_parts = array();
            if (!empty($company_city)) $location_parts[] = $company_city;
            if (!empty($company_pincode)) $location_parts[] = $company_pincode;
            if (!empty($company_state)) $location_parts[] = $company_state;
            if (!empty($location_parts)) echo implode(', ', $location_parts) . '<br>';
            ?>
            <?php
            $contact_parts = array();
            if (!empty($company_mobile)) $contact_parts[] = 'Mobile: ' . $company_mobile;
            if (!empty($company_phone)) $contact_parts[] = 'Phone: ' . $company_phone;
            if (!empty($contact_parts)) echo implode(' | ', $contact_parts) . '<br>';
            ?>
            <?php if (!empty($company_email)) echo 'Email: ' . $company_email . '<br>'; ?>
            <?php if (!empty($company_gstin)) echo 'GSTIN: ' . $company_gstin . '<br>'; ?>
            <?php if (!empty($company_tax_number)) echo 'Tax No: ' . $company_tax_number . '<br>'; ?>
        </td>
    </tr>
</table>

<div class="document-title">DELIVERY NOTE</div>

<!-- Delivery Details -->
<table class="header-table" style="margin-bottom: 15px;">
    <tr>
        <td style="width: 50%; vertical-align: top;">
            <strong>Deliver To:</strong><br>
            <strong><?= $customer_name; ?></strong><br>
            <?php if (!empty($customer_address)) echo $customer_address . '<br>'; ?>
            <?php if (!empty($customer_city)) echo $customer_city; ?>
            <?php if (!empty($customer_postcode)) echo ' - ' . $customer_postcode; ?>
            <?php if (!empty($customer_state)) echo ', ' . $customer_state; ?>
            <?php if (!empty($customer_country)) echo ', ' . $customer_country; ?><br>
            <?php if (!empty($customer_mobile)) echo 'Mobile: ' . $customer_mobile . '<br>'; ?>
            <?php if (!empty($customer_phone)) echo 'Phone: ' . $customer_phone . '<br>'; ?>
            <?php if (!empty($customer_email)) echo 'Email: ' . $customer_email . '<br>'; ?>
        </td>
        <td style="width: 50%; vertical-align: top; text-align: right;">
            <table class="no-border" style="float: right;">
                <tr>
                    <td><strong>Delivery Note No:</strong></td>
                    <td><?= $sales_code; ?></td>
                </tr>
                <tr>
                    <td><strong>Date:</strong></td>
                    <td><?= date('d-m-Y', strtotime($sales_date)); ?></td>
                </tr>
                <?php if (!empty($reference_no)) { ?>
                <tr>
                    <td><strong>Reference:</strong></td>
                    <td><?= $reference_no; ?></td>
                </tr>
                <?php } ?>
                <?php if (!empty($lpo_number)) { ?>
                <tr>
                    <td><strong>L.P.O Number:</strong></td>
                    <td style="font-weight: bold; color: #337ab7;"><?= $lpo_number; ?></td>
                </tr>
                <?php } ?>
            </table>
        </td>
    </tr>
</table>

<!-- Items Table -->
<table width="100%">
    <thead>
        <tr style="background-color: #f0f0f0;">
            <th style="width: 5%;">#</th>
            <th style="width: 50%;">Item Description</th>
            <th style="width: 15%; text-align: center;">Unit</th>
            <th style="width: 15%; text-align: center;">Quantity</th>
            <th style="width: 15%; text-align: center;">Received</th>
        </tr>
    </thead>
    <tbody>
<?php
    $i=0;
    $tot_qty=0;
    $q2=$this->db->query("SELECT c.item_name, a.sales_qty, a.unit_type, a.sales_qty_main, a.sales_qty_alternate,
                          a.batch_number, a.manufacturing_date, a.expiry_date, c.batch_tracking_enabled,
                          c.main_unit_id, c.alternate_unit_id, um.unit_name as main_unit_name, ua.unit_name as alternate_unit_name
                          FROM db_salesitems AS a
                          JOIN db_items AS c ON c.id = a.item_id
                          LEFT JOIN db_units um ON um.id = c.main_unit_id
                          LEFT JOIN db_units ua ON ua.id = c.alternate_unit_id
                          WHERE a.sales_id='$sales_id'");
    foreach ($q2->result() as $res2) {
        echo "<tr>";
        echo "<td style='text-align: center;'>".++$i."</td>";
        echo "<td>".$res2->item_name;

        // Display batch details if batch tracking is enabled
        if(false && $res2->batch_tracking_enabled == 1 && !empty($res2->batch_number)) {
            echo "<br><small><strong>Batch:</strong> ".$res2->batch_number;
            if(!empty($res2->expiry_date) && $res2->expiry_date != '0000-00-00') {
                $formatted_exp_date = date('d-m-Y', strtotime($res2->expiry_date));
                // Calculate days to expiry
                $today = new DateTime();
                $expiry = new DateTime($res2->expiry_date);
                $diff = $today->diff($expiry);
                $days_remaining = $diff->invert ? -$diff->days : $diff->days;
                $days_style = '';
                $days_label = '';
                if($days_remaining < 0) {
                    $days_style = 'color:#d9534f;';
                    $days_label = 'Expired';
                } elseif($days_remaining <= 30) {
                    $days_style = 'color:#f0ad4e;';
                    $days_label = $days_remaining.'d';
                } else {
                    $days_style = 'color:#5cb85c;';
                    $days_label = $days_remaining.'d';
                }
                echo " | <strong>Exp:</strong> ".$formatted_exp_date." <span style='".$days_style."'>(".$days_label.")</span>";
            }
            echo "</small>";
        }
        echo "</td>";

        // Determine unit name based on unit_type
        $unit_type = isset($res2->unit_type) ? $res2->unit_type : 'main';
        $main_unit_name = !empty($res2->main_unit_name) ? $res2->main_unit_name : '';
        $alt_unit_name  = !empty($res2->alternate_unit_name) ? $res2->alternate_unit_name : '';

        if ($unit_type == 'alternate' && !empty($alt_unit_name)) {
            $unit_display = $alt_unit_name;
            $qty_display = isset($res2->sales_qty_alternate) && $res2->sales_qty_alternate > 0 ? $res2->sales_qty_alternate : $res2->sales_qty;
        } else {
            $unit_display = $main_unit_name;
            $qty_display = isset($res2->sales_qty_main) && $res2->sales_qty_main > 0 ? $res2->sales_qty_main : $res2->sales_qty;
        }

        echo "<td style='text-align: center;'>".$unit_display."</td>";
        echo "<td style='text-align: center;'>".number_format($qty_display, 2)."</td>";
        echo "<td style='text-align: center;'></td>"; // Empty cell for "Received" signature
        echo "</tr>";
        $tot_qty += $qty_display;
    }
?>
    </tbody>
    <tfoot>
        <tr style="background-color: #f0f0f0;">
            <td colspan="3" style="text-align: right; font-weight: bold;">Total Items: <?= $i; ?></td>
            <td style="text-align: center; font-weight: bold;"><?= number_format($tot_qty, 2); ?></td>
            <td></td>
        </tr>
    </tfoot>
</table>

<?php if(!empty($sales_note)) { ?>
<table class="header-table" style="margin-top: 15px;">
    <tr>
        <td><strong>Note:</strong> <?= $sales_note; ?></td>
    </tr>
</table>
<?php } ?>

<!-- Signature Section -->
<table class="header-table" style="margin-top: 40px;">
    <tr>
        <td style="width: 50%; text-align: center;">
            <div style="border-top: 1px solid black; margin-top: 50px; padding-top: 5px;">
                <strong>Delivered By</strong><br>
                <small>Name & Signature</small>
            </div>
        </td>
        <td style="width: 50%; text-align: center;">
            <div style="border-top: 1px solid black; margin-top: 50px; padding-top: 5px;">
                <strong>Received By</strong><br>
                <small>Name, Signature & Date</small>
            </div>
        </td>
    </tr>
</table>

<?php if(!empty($sales_invoice_footer_text)) { ?>
<div style="text-align: center; margin-top: 20px; font-style: italic;">
    <?= $sales_invoice_footer_text; ?>
</div>
<?php } ?>

<!-- Print Button (hidden when printing) -->
<div class="no-print" style="text-align: center; margin-top: 20px;">
    <button type="button" onclick="window.print();" style="padding: 10px 20px; font-size: 16px; cursor: pointer;">
        Print Delivery Note
    </button>
</div>

</body>
</html>
