<?php
//You can take into consideration if you have the quantity amount in the items table, every time the order is made, to decrease the quantity of the item.

 include 'connect.php';
$order_price=$_POST['order_price'];
//comment
$order_delivery = $_POST['order_delivery'];
$total_price = $_POST['total_price'];
$order_city=$_POST['order_city'];
$item_list = $_POST["item_list"];
$order_address = $_POST["order_address"];
$userName=$_POST['username'];
$userPhone=$_POST['phoneNumber'];
$userEmail=$_POST['userEmail'];
$orderNotes=$_POST['order_notes'];
$data = json_decode($item_list, true);
date_default_timezone_set('Asia/Beirut');
$currentDateTime = date('Y-m-d H:i:s');

// $order_price=90;
// $order_city="saida";
// $item_list ='[[{
//       "specification_id": 4,"quantity": 3,"price": 10},{"specification_id":5,"quantity": 5,"price": 12}]]';
// $order_address = "Haret Saida in front of school";
// $userName="Youssef Yassine";
// $userPhone="+961 70997747";
// $userEmail="elzeinali803@gmail.com";
// $orderNotes="arrive at 5 pm";
// $data = json_decode($item_list, true);
// if ($data === null) {
//     echo "Error decoding JSON: " . json_last_error_msg();
// }
// date_default_timezone_set('Asia/Beirut');
// $currentDateTime = date('Y-m-d H:i:s'); 


$order_date = date('Y-m-d', strtotime($currentDateTime));
$order_time = date('H:i:s', strtotime($currentDateTime));

$order_date_string =(string) $order_date; 
$order_time_string =(string) $order_time;

$sql = "INSERT INTO a_orders (OrderPrice,OrderDelivery,TotalPrice, OrderDate, OrderTime, OrderCity, OrderAddress, UserFullName,UserPhoneNumber,UserEmail,OrderNotes)
        VALUES (?,?,?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "dddssssssss", $order_price,$order_delivery,$total_price, $order_date_string, $order_time_string, $order_city, $order_address, $userName,$userPhone,$userEmail,$orderNotes);
$result1 = mysqli_stmt_execute($stmt);

if($result1){
    $order_id=mysqli_insert_id($con);
    $response = array("status" => "orderAccepted");
    echo json_encode($response);
    $message = '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fabcart</title>
    <style>
        body,html{
            background-color: #19B387; 
            margin: 0;
            padding: 0;
            width:100%
        }
        h1,h2,h3,h4,h5,h6{
            margin: 0;
            padding: 0;
        }
        p{
            margin: 0;
            padding: 0;
        }
        .container{
            width: 80%;
            margin-right: auto;
            margin-left: auto;
        }
        .brand-section{
           background-color: green;
           padding: 10px 40px;
        }
        .logo{
            width: 50%;
        }

        .row{
            display: flex;
            flex-wrap: wrap;
        }
        .col-6{
            width: 50%;
            flex: 0 0 auto;
        }
        .text-white{
            color: white;
        }
        .company-details{
            float: right;
            text-align: right;
        }
        .body-section{
            padding: 16px;
            border: 1px solid gray;
        }
        .heading{
            font-size: 16px;
            margin-bottom: 08px;
        }
        .sub-heading{
            color: #262626;
            font-size:12px;
            margin-bottom: 05px;
        }
        table{
            padding: 0;
            background-color: #fff;
            width: 100%;
            border-collapse: collapse;
        }
        .container {
             width: 100%;
            margin: 0 ;
            }
        td {
              margin: 0;
                padding: 0;
                font-size:12px;
            }
        table thead tr{
            border: 1px solid #111;
            background-color: #f2f2f2;
        }
        table td {
            vertical-align: middle !important;
            text-align: center;
                font-size:12px;
        }
        table th, table td {
            padding-top: 08px;
            padding-bottom: 08px;
        }
        .table-bordered{
            box-shadow: 0px 0px 5px 0.5px gray;
        }
        .table-bordered td, .table-bordered th {
            border: 1px solid #dee2e6;
        }
        .text-right{
            text-align: end;
        }
        .w-20{
            width: 20%;
        }
        .float-right{
            float: right;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="brand-section">
            <div class="row">
                <div class="col-6">
                    <h4 class="text-white"> Namleyit Setti</h4>
                </div>
                <div class="col-6">
                    <div class="company-details">
                        <p class="text-white">+961 71440121</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="body-section">
            <div class="row">
                <div class="col-6">
                    <p class="sub-heading">Order Date: ' . $order_date . '</p>
                    <p class="sub-heading">Email Address: ' . $userEmail . '</p>
                     <p class="sub-heading">Phone Number: ' . $userPhone . '</p>
                </div>
                <div class="col-6">
                    <p class="sub-heading">Full Name: ' . $userName . '</p>
                    <p class="sub-heading">Address: ' . $order_address . '</p>
                    <p class="sub-heading">City: ' . $order_city . '</p>
                </div>
            </div>
        </div>

        <div class="body-section">
            <h3 class="heading">Ordered Items</h3>
            <br>
            <table class="table-bordered">
                <thead>
                    <tr>
                        <th>Product</th>
                        <th>Size</th>
                        <th class="w-20">Price</th>
                        <th class="w-20">Quantity</th>
                        <th class="w-20">Total</th>
                    </tr>
                </thead>
                <tbody>';
    // Transfer items from item_list sent from flutter to order_details
    foreach ($data as $items) {
        foreach($items as $item){
    $specification_id = $item['specId'];
    $itemName=$item['itemName'];
    $speciName=$item['specName'];
    $qty = $item['virutalQuantity'];
    $price = $item['price'];
    $total=$qty*$price;
    // Insert the data into the order_details table
    $query = "INSERT INTO a_orderdetails (D_SpecificationId_FK, D_Quantity,D_Price,D_Total,OrderID_FK) VALUES ($specification_id, $qty, $price,$total,$order_id)";
    $result_insert=mysqli_query($con, $query);
    if(!$result_insert){
        echo mysqli_error($con);
    }
    //To get the quantity of each specification
    $selectQty_query="SELECT S_quantity FROM a_specifications WHERE SpecificationID=$specification_id";
    $result_select=mysqli_query($con,$selectQty_query);
    $row_getQty=mysqli_fetch_assoc($result_select);
    $speci_qty=$row_getQty['S_quantity'];
    
    //Substract the quantity given from the result by the quantity the customer ordered
    $updateQty_query="UPDATE a_specifications SET S_quantity=$speci_qty-$qty WHERE SpecificationID=$specification_id";
        $result_update=mysqli_query($con,$updateQty_query);
    if(!$result_update){
        echo mysqli_error($con);
    }
     $message .= '<tr>
                            <td>' . $itemName . '</td>
                            <td>' . $speciName . '</td>
                            <td>' . $price . '</td>
                            <td>' . $qty . '</td>
                            <td>' . $total . '</td>
                        </tr>';
        }  
    }

$to = $userEmail; // The recipient's email address
$subject = 'Thanks For Your Order!';

$grandTotal = $order_price;

    // Add Grand Total row
    $message .= '<tr>
                    <td colspan="4" class="text-right">SubTotal</td>
                    <td>' . $grandTotal . '$</td>
                </tr>';
	   $message .= '<tr>
                    <td colspan="4" class="text-right">Delivery Charge</td>
                    <td>' . $order_delivery . '$</td>
                </tr>';
				
		$message .= '<tr>
                    <td colspan="4" class="text-right">Grand Total</td>
                    <td>' . $total_price . '$</td>
                </tr>';		
    // Complete the email template
    $message .= '</tbody>
                </table>
                <br>
                <h3 class="heading">Payment Mode: Cash on Delivery</h3>
            </div>

            <div class="body-section">
                <p>&copy; Copyright 2023 - Namleyit Setti. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>';


// Set the email headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
$headers .= "From: namliyatsiti@gmail.com";

// Send the email
if (mail($to, $subject, $message, $headers)) {
    echo 'Email sent successfully';
} else {
    echo 'Email sending failed';
}

}
     else {
         
        echo json_encode(array("status" => "notAccepted"));
    }
?>