<?php
session_start();
include('accesscheck2.php');
require_once('Connections/courier.php');
require_once('functions/functions.php');

$action = $_POST["act"];
$id = $_POST['id'];

$supplier = $_POST['supplier'];
$supplier_address = $_POST['supplier_address'];
$memo = $_POST['memo'];
$delivery_location = $_POST['delivery_location'];
$delivery_address = $_POST['delivery_address'];
$expected_date = $_POST['expected_date'];
$user_id = $_SESSION['myMM_Userid'];
$user_name = $_SESSION['myMM_Fullname'];
$purchase_id = $_POST['purchase_order_id'];

$promo_id = $_POST['promo_id'];
$start_time = $_POST['start_time'];
$end_time = $_POST['end_time'];
$promotion_name = $_POST['promotion_name'];
$promotion_description = $_POST['promotion_description'];
$promotionbranch = $_POST['promotionbranch'];

if ($action == 'edit_purchase_details' || $action == "edit_purchase_details_pending" || $action == 'edit_purchase_details_code') {

    if ($action == 'edit_purchase_details_code') {
        $queryItems = "SELECT * FROM stock_items WHERE id='$id'";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);

        if ($totalRows > 0) {
            $id = $arrayItems['id'];
        } else {
            $id = '';
        }
    }

    if ($id > 0) {
        $query_insert = "UPDATE purchase_orders set supplier='$supplier', supplier_address='$supplier_address', delivery_location='$delivery_location', delivery_address='$delivery_address', expected_date='$expected_date', memo='$memo', supplier_opening_balance='$supplier_opening_balance', user_id='$user_id' ,user_name='$user_name' where purchase_order_no='$purchase_id';";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $queryItems = "SELECT * FROM stock_items WHERE id='$id'";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);

        $item_id = $arrayItems['id'];
        $ins_item_code = $arrayItems['ins_item_code'];
        $item = $arrayItems['item'];
        $service = $arrayItems['service'];
        $alternate_lookup = $arrayItems['alternate_lookup'];
        $cost_price_before_tax = $arrayItems['cost_price'];

        $queryItems = "SELECT * FROM purchase_order_details WHERE purchase_order_no='$purchase_id' and item_id='$item_id' and pack_size=1";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);


        if ($totalRows > 0) {
            $item_qty = $arrayItems['qty_expected'] + 1;
            $total_price = $item_qty * $cost_price_before_tax;

            $query_insert = "update purchase_order_details set qty_expected='$item_qty' where purchase_order_no='$purchase_id' and item_id='$id'";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

            $status = 'success';
            $message = 'Quantity has been increased from ' . $arrayItems['qty_expected'] . ' to ' . $item_qty . ' - ' . strtoupper($item);
        } else {
            $item_qty = 1;
            $item_order_status = 'Outstanding';

            $status = 'success';
            $message = strtoupper($item) . ' has been added to the list Successfully !';

            $query_insert = "INSERT INTO `purchase_order_details` (`id`, `purchase_order_no`, `item_id`, `ins_item_code`, `item`, `service`, `qty_expected`, `qty_received`, `cost_price_before_tax`, `date_expected`, `datetime_received`, `item_order_status`, `pack_size`) VALUES (NULL, '$purchase_id', '$item_id',  '$ins_item_code', '$item', '$service', '$item_qty', '$qty_received', '$cost_price_before_tax', '$expected_date', '$datetime_received', '$item_order_status', '$pack_size_qty');";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
        }
    }
    echo $status . '@@@' . $message . '@@@';
    if($action == "edit_purchase_order_pending"){
        $action = "edit_purchase_order_pending";
    }
    include('list_of_added_items.php');
}


if ($action == 'del_purchase_order_details') {
    $query_insert = "delete from purchase_order_details where id='$id';";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    include('list_of_added_items.php');
}

if ($action == 'up_purchase_order_details') {
    $queryItems = "SELECT * FROM purchase_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);

    $resultItems2 = mysql_query("SELECT item FROM service_items WHERE id='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if ($totalRows > 0) {
        $item_qty = $arrayItems['qty_expected'] + 1;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];

        $query_insert = "update purchase_order_details set qty_expected='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $status = 'success';
        $message = "Quantity has been Increased from " . $arrayItems['qty_expected'] . " to $item_qty - " . strtoupper($item);
        echo $status . '@@@' . $message . '@@@';
    }
    include('list_of_added_items.php');
}


if ($action == 'down_purchase_order_details') {
    $queryItems = "SELECT * FROM purchase_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);

    $resultItems2 = mysql_query("SELECT item FROM service_items WHERE id='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if (($totalRows > 0) && ($arrayItems['qty_expected'] > 1)) {
        $item_qty = $arrayItems['qty_expected'] - 1;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];

        $query_insert = "update purchase_order_details set qty_expected='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $status = 'success';
        $message = "Quantity has been Decreased from " . $arrayItems['qty_expected'] . " to $item_qty - " . strtoupper($item);
        echo $status . '@@@' . $message . '@@@';
    }
    include('list_of_added_items.php');
}

if ($action == 'updateqty_purchase_order_details') {
    $value = $_POST["value"];
    $next_action_val = $_POST["next_action_val"];
    $queryItems = "SELECT * FROM purchase_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);
    $unit_price = $arrayItems['qty_expected'];

    $resultItems2 = mysql_query("SELECT item FROM service_items WHERE id='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if ($totalRows > 0) {
        $item_qty = $value;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];
        $query_insert = "update purchase_order_details set qty_expected='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        if ($value > $unit_price) {
            $status = 'success';
            $message = "Quantity has been Increased from $unit_price to $value - " . strtoupper($item);
        } else if ($value < $unit_price) {
            $status = 'success';
            $message = "Quantity has been Decreased from $unit_price to $value - " . strtoupper($item);
        }
        echo $status . '@@@' . $message . '@@@';
    }
    if($next_action_val == 'save_purchase_order_pending'){
        $action = 'edit_purchase_order_pending';
    }
    include('list_of_added_items.php');
}


if ($action == 'updateprice_purchase_order_details') {
    $value = $_POST["value"];
    $next_action_val = $_POST["next_action_val"];
    $queryItems = "SELECT * FROM purchase_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);
    $unit_price = $arrayItems['cost_price_before_tax'];

    $resultItems2 = mysql_query("SELECT item FROM service_items WHERE id='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if ($totalRows > 0) {
        $item_qty = $value;
        $total_claim = $item_qty * $arrayItems['qty_expected'];

        $query_insert = "update purchase_order_details set cost_price_before_tax='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        if ($value > $unit_price) {
            $status = 'success';
            $message = "Price has been Increased from $unit_price to $value - " . strtoupper($item);
        } else if ($value < $unit_price) {
            $status = 'success';
            $message = "Price has been Decreased from $unit_price to $value - " . strtoupper($item);
        }
        echo $status . '@@@' . $message . '@@@';
    }
    if($next_action_val == 'save_purchase_order_pending'){
        $action = 'edit_purchase_order_pending';
    }
    include('list_of_added_items.php');
}


if ($action == 'updatepacksize_purchase_order_details') {
    $totalqty = $_POST["value"];
    $queryItems = "SELECT * FROM purchase_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);

    $item_id = $arrayItems['item_id'];


    if ($totalRows > 0) {
        $item_qty = $totalqty;

        $query_insert = "update purchase_order_details set pack_size='$item_qty', cost_price_before_tax='$packprice'  where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier);
        echo mysql_error();
    }
    
    include('list_of_added_items.php');
}

if($action=="delete_purchase_order"){
	$del_purchase_details = mysql_query("DELETE FROM purchase_order_details where purchase_order_no='$id'")or die ("could not del purchase items".mysql_error());
	$del_purchase_order = mysql_query("DELETE FROM purchase_orders where purchase_order_no='$id'")or die ("could not delete purchase_order".mysql_error());
	include("list_purchase_orders.php");
}

if ($action == 'save_purchase_order' || $action == "save_purchase_order_pending") {
    if ($action == 'save_purchase_order'){
        $text = "Saved";
    $rsupdate_records = mysql_query("update purchase_orders set order_status='Saved', supplier='$supplier', supplier_address='$supplier_address', memo='$memo', delivery_location='$delivery_location', delivery_address='$delivery_address', expected_date='$expected_date', approval_status = 'Approved' where purchase_order_no='$id'") or die(mysql_error());
    }else if($action == "save_purchase_order_pending"){
        $text = "Approved";
    $rsupdate_records = mysql_query("update purchase_orders set order_status='Saved',approval_status='Approved',date_of_approval=now(),approved_by='".$_SESSION['myMM_Username']."',supplier='$supplier', supplier_address='$supplier_address', memo='$memo', delivery_location='$delivery_location', delivery_address='$delivery_address', expected_date='$expected_date' where purchase_order_no='$id'") or die(mysql_error());
    }
    if ($rsupdate_records == TRUE) {
        echo "Success! Purchase Order Details $text Successfully.@@@success@@@";
    } else {
        echo 'Oops! Failed to Save Purchase Order Details.@@@error@@@';
    }
    if($action == "save_purchase_order_pending"){
        $action = 'list_purchase_orders_pending';
    }
        include 'list_purchase_orders.php';
}
    
if($action=="supplier_address"){
$query_rspics = "select * FROM suppliers where id='$id'";
$rspics = mysql_query($query_rspics, $courier) or die(mysql_error()); 
$row_rspics=mysql_fetch_assoc($rspics);
echo $row_rspics['supplier_address'];
}

if($action=="delivery_address"){
$query_rspics = "select * FROM departments where id='$id'";
$rspics = mysql_query($query_rspics, $courier) or die(mysql_error()); 
$row_rspics=mysql_fetch_assoc($rspics);
echo $row_rspics['department_address'];
}

if ($action == 'add_new_purchase_order' || $action == 'add_new_purchase_order_pending') {
    $query_ipaddress = "select SUBSTRING_INDEX(host,':',1) as 'ip' from information_schema.processlist where ID=connection_id();";
    $rsipaddress = mysql_query($query_ipaddress, $courier) or die(mysql_error());
    $row_rsipaddress = mysql_fetch_assoc($rsipaddress);

    $user_ipaddress = $row_rsipaddress['ip'];
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    $order_status = "Not Saved";

    $query_insert = "INSERT INTO `purchase_orders` (`purchase_order_no`, `supplier`, `supplier_address`, `date_of_order`, `delivery_location`, `delivery_address`, `expected_date`,  `supplier_message`, `memo`, `supplier_opening_balance`, `order_status`, `user_ipaddress`, `user_id`, `user_name`, `branch_id`) VALUES (NULL, '$supplier', '$supplier_address', NOW(), '$delivery_location', '$delivery_address', '$expected_date', '$supplier_message', '$memo', '$supplier_opening_balance', '$order_status', '$user_ipaddress', '$user_id', '$user_name','".$_SESSION['branch_id_user']."');";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    $id = mysql_insert_id();
    include 'edit_purchase_order.php';
}

if ($action == 'updateprice_purchase_order_details_actual') {
    $value = $_POST["value"];
    $queryItems = "SELECT * FROM purchase_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);
    $unit_price = $arrayItems['received_price'];

    $resultItems2 = mysql_query("SELECT item FROM service_items WHERE id='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];

    if ($totalRows > 0) {
        $item_qty = $value;
        $total_claim = $item_qty * $arrayItems['qty_expected'];

        $query_insert = "update purchase_order_details set received_price='$item_qty' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        if ($value > $unit_price) {
            $status = 'success';
            $message = "Actual Price has been Increased from $unit_price to $value - " . strtoupper($item);
        } else if ($value < $unit_price) {
            $status = 'success';
            $message = "Actual Price has been Decreased from $unit_price to $value - " . strtoupper($item);
        }
        echo $status . '@@@' . $message . '@@@';
    }
    $purchase_id = $arrayItems['purchase_order_no'];
    include('list_items_received.php');
}

if ($action == 'updateqty_purchase_order_details_actual') {
    $value = $_POST["value"];
    $queryItems = "SELECT * FROM purchase_order_details WHERE id='$id' ";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);
    $unit_price = $arrayItems['qty_received'];
    $qty_expected = $arrayItems['qty_expected'];

    $resultItems2 = mysql_query("SELECT item FROM service_items WHERE id='" . $arrayItems['item_id'] . "'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item = $arrayItems2['item'];
    if ($qty_expected == $value) {
         $match = 'Yes';
        $poStatus = 'Closed';
    }else{
         $match = 'No';
    }
    
    if ($value > $qty_expected) {
        $status = 'error';
        $message = "Actual Quantity cannot be more than expected qantity - " . strtoupper($item);
        echo $status . '@@@' . $message . '@@@';
    }else{
        if ($totalRows > 0) {
        $item_qty = $value;
        $total_claim = $item_qty * $arrayItems['item_unit_price'];
        $query_insert = "update purchase_order_details set qty_received='$item_qty', qty_match = '$match', qty_mismatch_status='$poStatus' where id='$id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        if ($value > $unit_price) {
            $status = 'success';
            $message = "Actual Quantity has been Increased from $unit_price to $value - " . strtoupper($item);
        } else if ($value < $unit_price) {
            $status = 'success';
            $message = "Actual Quantity has been Decreased from $unit_price to $value - " . strtoupper($item);
        }
        echo $status . '@@@' . $message . '@@@';
    }
    }

    


    $purchase_id = $arrayItems['purchase_order_no'];
    include('list_items_received.php');
}

if ($action == 'closepo') {
    $id = $_POST["id"];
    $purchase_id = $_POST['orderno'];
    $rsupdate_records = mysql_query("UPDATE purchase_order_details SET qty_mismatch_status='Closed' WHERE id='$id'");
    if ($rsupdate_records){
        $bill_amt_info_qty = mysql_fetch_assoc(mysql_query("SELECT * FROM purchase_order_details WHERE id ='$id'"));
        $bill_qty_received = $bill_amt_info_qty['qty_received'];
        $bill_qty_item_id = $bill_amt_info_qty['item_id'];
        $namecode = $_SESSION['name_code'];
        //echo "UPDATE stock_items SET quantity_available = '$bill_qty_received' WHERE id = '$bill_qty_item_id'";
        $update_branch_qty = mysql_query("UPDATE stock_items SET quantity_available = '$bill_qty_received' WHERE id = '$bill_qty_item_id'");
    }
    include('list_items_received.php');
}

if ($action == 'save_received_order' || $action == "save_received_order_approved") {
    $supplier_opening_balance = $_POST['supplier_opening_balance'];
    $bill_ref = $_POST['bill_ref'];
    // $bill_amt = $_POST['bill_amt'];
    $bill_discount = $_POST['bill_discount'];
    $bill_date = $_POST['bill_date'];
    $bill_due_date = $_POST['bill_due_date'];
    $received_date = $_POST['received_date'];
    $delivery_memo = $_POST['delivery_memo'];
    $bill_due_date = $_POST['bill_due_date'];
    $supplier_id = $_POST['supplier_id'];

    if ($action == 'save_received_order'){
    $bill_amt_info = mysql_fetch_assoc(mysql_query("SELECT SUM(qty_received*received_price) AS totalcost FROM purchase_order_details WHERE purchase_order_no='$id'"));
    $bill_amt = $bill_amt_info['totalcost'];
    
    $rsupdate_records = mysql_query("update purchase_orders set received_by='".$_SESSION['myMM_Username']."', date_of_received=now(), order_status='Received', supplier_opening_balance='$supplier_opening_balance', bill_ref='$bill_ref', bill_amt='$bill_amt', bill_discount='$bill_discount', bill_date='$bill_date', bill_due_date='$bill_due_date', received_date='$received_date', delivery_memo='$delivery_memo',receive_approval_status = 'Approved'  where purchase_order_no='$id'") or die(mysql_error());
    $type_of_transaction = 'bill';
    $debit_credit = 'credit';
    $credit_amt = $bill_amt;
    $amount = $bill_amt;
    $query = mysql_query("INSERT INTO `suppliers_bill_payments` (`id`, `supplier_id`, `type_of_transaction`, `amount`, `bill_date`, `bill_due_date`, `purchase_order_no`, `debit_credit`, `credit_amt`, `supplier_opening_balance`) VALUES (NULL, '$supplier_id', '$type_of_transaction', '$amount', '$bill_date', '$bill_due_date', '$id', '$debit_credit', '$credit_amt', '$supplier_opening_balance')") or die(mysql_error());
    
    if ($rsupdate_records){
        $bill_amt_info_qty = mysql_fetch_assoc(mysql_query("SELECT * FROM purchase_order_details WHERE purchase_order_no='$id'"));
        $bill_qty_received = $bill_amt_info_qty['qty_received'];
        $bill_qty_item_id = $bill_amt_info_qty['item_id'];
        $namecode = $_SESSION['name_code'];
        //echo"UPDATE service_items SET quantity_available_$namecode = '$bill_qty_received' WHERE id = '$bill_qty_item_id'";
        $update_branch_qty = mysql_query("UPDATE stock_items SET quantity_available = '$bill_qty_received' WHERE id = '$bill_qty_item_id'");
    }




    }

    if($action == "save_received_order_approved"){
    //UPDATE STOCK OF PROCUREMENT
    $stock_info = mysql_query("SELECT * FROM purchase_order_details WHERE purchase_order_no='$id' order by id desc;");
    $delivery_location_r = mysql_fetch_assoc(mysql_query("SELECT id FROM branches WHERE branch_code='ST' LIMIT 1"));
    $branch_id = $delivery_location_r['id'];
    while ($row = mysql_fetch_assoc($stock_info)) {
        $item_id = $row['item_id'];
        $item_info = mysql_fetch_assoc(mysql_query("SELECT id, quantity_available FROM stock_items WHERE item_id = '$item_id'"));
        $quantity_available = $item_info['quantity_available'] + $row['qty_received'];
        $rsupdate_records = mysql_query("UPDATE stock_items SET quantity_available = '$quantity_available' WHERE id = '" . $item_info['id'] . "'");
    }
        $rsupdate_records = mysql_query("UPDATE purchase_orders SET receive_approved_by='".$_SESSION['myMM_Username']."', date_of_receive_approval=now(), receive_approval_status='Approved' WHERE purchase_order_no='$id'");
}

    if ($rsupdate_records == TRUE) {
        echo 'Success! Order Received Successfully.@@@success@@@';
    } else {
        echo 'Oops! Failed to Received Order.@@@error@@@';
    }
    include 'list_received_items_not_completed.php';
}


if($action == "generate_all_purchase_order"){
    
    $job_numbers = $_POST['lens_job_no'];
    $user_ipaddress = $row_rsipaddress['ip'];
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    $order_status = "Saved";
    $item_order_status = 'Outstanding';
    $expected_date = date('Y-m-d');
    $branch_id = $_SESSION['branch_id'];
    // $branch_id_user = $_SESSION['branch_id_user'];

    $all_months = array('01'=> 1,'02'=>2,'03'=>3,'04'=>4,'05'=>5,'06'=>6,'07'=>7,'08'=>8,'09'=>9,'10'=>10,'11'=>11,'12'=>12);
    $month = date('m');
    $month2 = $all_months[$month];
    $job_no_max = mysql_fetch_assoc(mysql_query("SELECT MAX(batch_number_int) AS max_job_number FROM batch_numbers WHERE month_date='$month' AND branch_id='$branch_id'")); 
    $max_job_no_int = $job_no_max['max_job_number'] + 1;
    $batch_no = 'BA'.$month2.'/'.$max_job_no_int;
    mysql_query("INSERT INTO batch_numbers(batch_number_int,batch_number,month_date,branch_id) VALUES('$max_job_no_int','$batch_no','$month','$branch_id')");

    foreach($job_numbers AS $job_number){
        $supplier_id = $_POST['supplier_'.$job_number];
        $item_id = $_POST['item_id_'.$job_number];
        $process_claim_no = $_POST['process_claim_no_'.$job_number];

        if($supplier_id != '0'){
        $supplier_details = mysql_fetch_assoc(mysql_query("SELECT * FROM suppliers WHERE id='$supplier_id'"));
        $delivery_details = mysql_fetch_assoc(mysql_query("SELECT * FROM branches WHERE branch_code='PR'"));
        $supplier = $supplier_details['id'];
        $supplier_address = $supplier_details['supplier_address'];
        $delivery_location = $delivery_details['id'];
        $delivery_address = $delivery_address['postal_address'];

        $row = mysql_fetch_assoc(mysql_query("SELECT * FROM claims_details WHERE process_claim_no='$process_claim_no' AND job_number='$job_number' AND item_service_type='Optical Lens' LIMIT 1"));
        $item_id = $row['provider_item_id'];
        $ins_item_code = $row['ins_item_code'];
        $item = $row['item'];
        $service = $row['item_service_type'];
        $item_qty = $row['qty'];

        $supplier_message = "PURCHASE ORDER FOR JOB NUMBER $job_number. LENS/$item";
        $memo = "PURCHASE ORDER FOR JOB NUMBER $job_number. LENS/$item";
    
        $query_insert = "INSERT INTO `purchase_orders` (`order_type`,`po_batch_no`,`supplier`, `supplier_address`, `date_of_order`, `delivery_location`, `delivery_address`, `expected_date`,  `supplier_message`, `memo`, `supplier_opening_balance`, `order_status`, `user_ipaddress`, `user_id`, `user_name`, `branch_id`,`process_claim_no`,`approval_status`,`date_of_approval`,`approved_by`) VALUES ('Lens Order','$batch_no','$supplier', '$supplier_address', NOW(), '$delivery_location', '$delivery_address', '$expected_date', '$supplier_message', '$memo', '$supplier_opening_balance', '$order_status', '$user_ipaddress', '$user_id', '$user_name','$branch_id','$process_claim_no','Approved',now(),'$user_name');";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
        $purchase_id = mysql_insert_id();

        $query_insert = "INSERT INTO `purchase_order_details` (`id`, `purchase_order_no`, `item_id`, `ins_item_code`, `item`, `service`, `qty_expected`, `cost_price_before_tax`, `date_expected`, `item_order_status`, `pack_size`) VALUES (NULL, '$purchase_id', '$item_id',  '$ins_item_code', '$item', '$service', '$item_qty', '$cost_price_before_tax', '$expected_date', '$item_order_status', '$pack_size_qty');";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $insert = mysql_query("UPDATE claims_details SET po_status='Order Placed',po_batch_no='$batch_no' WHERE process_claim_no='$process_claim_no' AND job_number='$job_number' AND item_service_type='Optical Lens'");
        }
    }
}


if ($action == 'add_new_promotion') {
    $query_ipaddress = "select SUBSTRING_INDEX(host,':',1) as 'ip' from information_schema.processlist where ID=connection_id();";
    $rsipaddress = mysql_query($query_ipaddress, $courier) or die(mysql_error());
    $row_rsipaddress = mysql_fetch_assoc($rsipaddress);

    $user_ipaddress = $row_rsipaddress['ip'];
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    $order_status = "Not Saved";


    $query_insert = "INSERT INTO `promotion_order`(`promotion_name`, `promotion_decription`, `start_date`, `end_date`, `user_id`,`user_ipaddress`,`user_fullname`) VALUES ('$promotion_name', '$promotion_description', '$start_date', '$end_date', '$user_id','$user_ipaddress','$user_name')";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    $id = mysql_insert_id();
    include 'promotional_sales.php';
}


if ($action == 'edit_promo_details') {
    $query_ipaddress = "select SUBSTRING_INDEX(host,':',1) as 'ip' from information_schema.processlist where ID=connection_id();";
    $rsipaddress = mysql_query($query_ipaddress, $courier) or die(mysql_error());
    $row_rsipaddress = mysql_fetch_assoc($rsipaddress);

    $user_ipaddress = $row_rsipaddress['ip'];
    $user_id = $_SESSION['myMM_Userid'];
    $user_name = $_SESSION['myMM_Fullname'];
    //echo $id;
    if ($id > 0) {
        $query_insert = "UPDATE `promotion_order` SET `promotion_name` = '$promotion_name', `promotion_decription` = '$promotion_description', `start_date` = '$start_time', `end_date` = '$end_time' WHERE `id` = '$promo_id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $queryItems = "SELECT * FROM service_items WHERE id='$id'";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);

        $item_id = $arrayItems['id'];
        $ins_item_code = $arrayItems['ins_item_code'];
        $item = $arrayItems['item'];
        $service = $arrayItems['service'];
        $service_type = $arrayItems['service_type'];
        $alternate_lookup = $arrayItems['alternate_lookup'];
        $cost_price_before_tax = $arrayItems['cost_price'];

        $queryItems = "SELECT * FROM promotion_order_details WHERE promo_id ='$promo_id' and item_id='$item_id'";
        $resultItems = mysql_query($queryItems) or die(mysql_error());
        $arrayItems = mysql_fetch_assoc($resultItems);
        $totalRows = mysql_num_rows($resultItems);


        if ($totalRows > 0) {
            $query_insert = "UPDATE promotion_order_details SET item_id = '$item_id', item_name = '$item', service_type = '$service_type'  WHERE promo_id ='$promo_id' and item_id='$item_id'";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

            $status = 'success';
            //$message = 'Quantity has been increased from ' . $arrayItems['qty_expected'] . ' to ' . $item_qty . ' - ' . strtoupper($item);
        } else {
            $item_qty = 1;
            $item_order_status = 'Outstanding';

            $status = 'success';
            //$message = strtoupper($item) . ' has been added to the list Successfully !';

            $query_insert = "INSERT INTO `promotion_order_details`(`promo_id`, `item_id`, `item_name`, `service_type`) VALUES ('$promo_id', '$item_id', '$item', '$service_type')";
            $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
        }
    }
    echo $status . '@@@' . $message . '@@@';
    if($action == "edit_purchase_order_pending"){
        $action = "edit_purchase_order_pending";
    }
    include('list_of_added_items_promo.php');
}


if ($action == "del_promo") {
    $delete_id = $_POST['id'];
    $getid = mysql_fetch_assoc(mysql_query("SELECT * FROM promotion_order_details WHERE id = '$delete_id'"));
    $delete = mysql_query("DELETE FROM promotion_order_details WHERE id = '$delete_id'");
    
    $promo_id = $getid['promo_id'];
    include('list_of_added_items_promo.php');
}


if ($action == "delete_purchase_order_promo") {
    $delete_id = $_POST['id'];
    $delete = mysql_query("DELETE FROM promotion_order_details WHERE promo_id = '$delete_id'");
    if ($delete) {
       $delete1 = mysql_query("DELETE FROM promotion_order WHERE id = '$delete_id'");
    }
    include('list_of_added_items_promo.php');
}

if ($action == "save_promo_order") {
     if ($id > 0) {
        $query_insert = "UPDATE `promotion_order` SET `promotion_name` = '$promotion_name', `promotion_decription` = '$promotion_description', `start_date` = '$start_time', `end_date` = '$end_time',`branch`='$promotionbranch' WHERE `id` = '$promo_id'";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    }else{
          $query_insert = "INSERT INTO `promotion_order`(`promotion_name`, `promotion_decription`, `start_date`, `end_date`, `user_id`,`user_ipaddress`,`user_fullname`) VALUES ('$promotion_name', '$promotion_description', '$start_date', '$end_date', '$user_id','$user_ipaddress','$user_name',`branch`='$promotionbranch')";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    $id = mysql_insert_id(); 
    }

    include 'promotional_sales.php'; 
}