<?php
include "../../root.class.php";
$email = new email();
$call = new call_functions();
$db = new db_safeguard();
echo "<script>alert('PLEASE WAIT FOR DISPATCH SUCCESSFULL TO POPUP, IF IT DOES NOT PLEASE CONTACT CP');</script>";
// var_dump($_POST);
$user_id = $_POST['user_id'];
$jc_number = $_POST['jc_number'];
$signature = $_POST['signature'];
$receiving = $_POST['receiving'];
$contractor = $_POST['contractor'];
$tech = 0;
$account = 0;
$project = 0;
echo "<br>";
var_dump($_POST);

echo "<br>";
echo "<br>
TYPE: ";
// get manager of project job card 
$jobcard_res = $db->query("job_cards", "SELECT * FROM job_cards WHERE jc_number = '$jc_number'");
if ($jobcard_res->num_rows == 0) {
    $jobcard_res = $db->query("job_cards_tech", "SELECT * FROM job_cards_tech WHERE jc_number = '$jc_number'");
    if ($jobcard_res->num_rows == 0) {
        $jobcard_res = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE `name` = '$jc_number'");
        $account = 1;
        echo "ACCOUNT";
    } else {
        $tech = 1;
        echo "TECH";
    }
} else {
    echo "PROJECT";
    echo "<br>";
    $project = 1;
}
echo "<br>";
$jobcard = $jobcard_res->fetch_assoc();
if ($tech == 1) {
    $manager_id = $jobcard['user_id'];
} else {
    $manager_id = $jobcard['account_manager_id'];
}
echo "manager id: " . $manager_id;
$date_time = date("Y-m-d H:i", strtotime("+2 Hours"));


// create disptach batch
$dispatch_id = $db->query('dispatch_batches', "INSERT INTO dispatch_batches (`jc_number`,`date_time`,`user_id`,`received_by`) VALUES('$jc_number','$date_time',$user_id,'$receiving')");

$index = 1;
$error = 0;
$items_for_email = "";
while ($index <= 200) {
    echo "<br>" . $stock_id = $_POST['stock_id_' . $index];
    echo "<br>";
    $amount = $_POST['amount_' . $index];
    $stock_details = explode("|", $_POST['stock_id_' . $index]);
    var_dump($stock_details);
    $stock_name = $stock_details[0];
    if (strlen($stock_id) > 0) {
        echo "DETAILS~ " . $stock_details[1];
        echo "<br>R-- " . $stock_record_id = substr($stock_details[1], strpos($stock_details[1], "R~") + 2, strpos($stock_details[1], "~R") - strpos($stock_details[1], "R~") - 2);
        echo "<br>";


        if (strpos($stock_id, "T~0~T") !== false) {
            echo "STOCK";
            $serial_number = "";
            $rec_id = $db->query("order_trans", "INSERT INTO order_trans (`stock_id`, `non_stock_id`, `amount`, `date_time`, `order_id`, `user_id`, `job_card_no`, `units_stock_id`,`signature`,`received`,`contractor`,`dispatch_batch_id`) VALUES ($stock_record_id,0,'-$amount','$date_time',0,$user_id,'$jc_number',0,'$signature','$receiving','$contractor','$dispatch_id')");
            $items_for_email .= "<tr style='border~1px solid black'><td>$stock_name</td><td>$amount</td><td>$serial_number</td></tr>";
            if ($rec_id < 1) {
                $error = 1;
                echo "INSERT INTO order_trans (`stock_id`, `non_stock_id`, `amount`, `date_time`, `order_id`, `user_id`, `job_card_no`, `units_stock_id`,`signature`,`received`,`contractor`,`dispatch_batch_id`) VALUES ($stock_record_id,0,'-$amount','$date_time',0,$user_id,'$jc_number',0,'$signature','$receiving','$contractor','$dispatch_id')";
            }

        } else {

            if (strpos($stock_id, "T~1~T") !== false) {
                echo "NON STOCK <br>";

                echo " <br> BARCODE ~ " . $barcode = substr($stock_id, strpos($stock_id, "B~") + 2, strpos($stock_id, "~B") - strpos($stock_id, "B~") - 2);
                $stock_id = substr($stock_id, strpos($stock_id, "R~") + 2, strpos($stock_id, "~R") - strpos($stock_id, "R~") - 2);
                // get the non stock id
                $non_stock_res = $db->query("non_stock", "SELECT * FROM non_stock WHERE barcode = '$barcode'");
                $non_stock = $non_stock_res->fetch_assoc();

                $record_id = $db->query("order_trans", "INSERT INTO order_trans (`stock_id`, `non_stock_id`, `amount`, `date_time`, `order_id`, `user_id`, `job_card_no`, `units_stock_id`,`signature`,`received`,`contractor`,`dispatch_batch_id`) VALUES ($stock_id,{$non_stock['record_id']},'-$amount','$date_time',0,$user_id,'$jc_number',0,'$signature','$receiving','$contractor','$dispatch_id')");

                $items_for_email .= "<tr style='border~1px solid black'><td>$stock_name</td><td>$amount</td><td>$serial_number</td></tr>";
                if ($record_id < 1) {
                    $error = 1;
                    echo "INSERT INTO order_trans (`stock_id`, `non_stock_id`, `amount`, `date_time`, `order_id`, `user_id`, `job_card_no`, `units_stock_id`,`signature`,`received`,`contractor`,`dispatch_batch_id`) VALUES ($stock_id,{$non_stock['record_id']},'-$amount','$date_time',0,$user_id,'$jc_number',0,'$signature','$receiving','$contractor','$dispatch_id')";
                }

            } else {
                echo "UNITS";

                echo "<br>S-- " . $serial_number = substr($stock_id, strpos($stock_id, "S~") + 2, strpos($stock_id, "~S") - strpos($stock_id, "S~") - 2);
                $res = $db->query("units_stock", "SELECT * FROM units_stock WHERE serial_number = '$serial_number'");
                $unit = $res->fetch_assoc();
                $unit_record_id = $unit['record_id'];
                $rec_id = 0;
                $rec_id = $db->query("order_trans", "INSERT INTO order_trans (`stock_id`, `non_stock_id`, `amount`, `date_time`, `order_id`, `user_id`, `job_card_no`, `units_stock_id`,`signature`,`received`,`contractor`,`dispatch_batch_id`) VALUES ($stock_record_id,0,'-$amount','$date_time',0,$user_id,'$jc_number',$unit_record_id,'$signature','$receiving','$contractor','$dispatch_id')");
                $items_for_email .= "<tr style='border~1px solid black'><td>$stock_name</td><td>$amount</td><td>$serial_number</td></tr>";
                if ($rec_id < 1) {
                    $error = 1;
                    echo "INSERT INTO order_trans (`stock_id`, `non_stock_id`, `amount`, `date_time`, `order_id`, `user_id`, `job_card_no`, `units_stock_id`,`signature`,`received`,`contractor`,`dispatch_batch_id`) VALUES ($stock_record_id,0,'-$amount','$date_time',0,$user_id,'$jc_number',$unit_record_id,'$signature','$receiving','$contractor','$dispatch_id')";
                }
            }
        }
        echo "<br>";
    }
    $index++;
}

$image_data = file_get_contents("signatures/" . $signature);

$jobcard_type = "";

if ($project == 1) {
    $jobcard_type = "<p>Project Name: " . $jobcard['project_name'] . "</p>";
    $email_name = $jobcard['project_name'];

} else if ($tech == 1) {
    $jobcard_type = "<p> Name: " . $jobcard['company_name'] . "</p>";
    $email_name = $jobcard['company_name'];

} else {
    $jobcard_type = "<p>Account Name: " . $jobcard['description'] . "</p>";
    $email_name = $jobcard['description'];
}

$disp = "";

if ($contractor != '') {
    $contractor = "<p>Contractor: " . $contractor . "</p>";
}
if ($contractor == '') {
    $image = "<img src='data:image/png;base64," . base64_encode($image_data) . "' width='200' height='100' />";
} else {
    $image = "<br> SIGNATURE: __________________________________";
    $disp = "To Site";
}
$email_html = "
            <html>
                <body>
                    <h5>Dispatch $disp</h5>
                    <p>Dispatched by: " . $call->get_username($user_id) . "</p>
                    <p>Job Card Number: " . $jc_number . "</p>
                    $jobcard_type
                    <p>Driver By: " . $receiving . "</p>
                    $contractor
                    $image
                  <table style='width:100%; text-align:center;border:1px solid black'>
                    <tr style='border:1px solid black'>
                        <th style='width:60%'>Item</th>
                        <th style='width:20%'>Amount</th>
                        <th style='width:20%'>Serial Number</th>
                    </tr>
                    " . $items_for_email . "
                  </table>
                  <a href='https://mas.elegantwork.co.za/app/stock_control/dispatch_pdf.php?dispatch_id=$dispatch_id' style='color:blue;font-size:40px'>PRINT</a>
                </body>
            </html>
            ";

$emails = ['stores@midrandac.co.za', 'alex@midrandac.co.za', 'anton@midrandac.co.za'];
$names = ['Stores', 'Alex', 'Anton'];
$user_res = $db->query("users", "SELECT * FROM users WHERE record_id = $manager_id");
$user = $user_res->fetch_assoc();
$emails[] = $user['email'];
$names[] = $user['username'];

// $emails[] = 'chris@elegantwork.co.za';
// $names[] = 'chris';

$email_html = mb_convert_encoding($email_html, 'HTML-ENTITIES', 'UTF-8');
$call->send_for_email($emails, $names, $jc_number . " - " . $email_name, $email_html);

if ($disp != "") {
    ?>
    <script>
        function sendPageHTMLAndContinue() {
            const html = document.documentElement.outerHTML;
            fetch('save_dispatch_log.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ html: html })
            }).then(() => {
                // After sending, redirect
                // window.location.href = targetUrl;
            }).catch(err => {
                console.error('Failed to send HTML:', err);
                // Still redirect if needed
                // window.location.href = targetUrl;
            });
        }
        sendPageHTMLAndContinue();
        window.location.href = "dispatch_to_site.php?disptach=1";
    </script>

    <?php
} else {
    ?>

    <script>
        function sendPageHTMLAndContinue() {
            const html = document.documentElement.outerHTML;
            fetch('save_dispatch_log.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ html: html })
            }).then(() => {
                // After sending, redirect
                // window.location.href = targetUrl;
            }).catch(err => {
                console.error('Failed to send HTML:', err);
                // Still redirect if needed
                // window.location.href = targetUrl;
            });
        }
        sendPageHTMLAndContinue();
        window.location.href = "dispatch.php?disptach=1";
    </script>

<?php } ?>