<?php
session_start();
include('dbcon.php');

$id = $_POST['id'];
$inq = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM tbl_inquiry WHERE id='$id'"));

// POST values
$service             = $_POST['service'];
$service_date        = $_POST['service_date'];
$service_tc          = $_POST['service_term_condition'];
$total_amount        = $_POST['total_amount'];
$warranty            = $_POST['warranty'];
$service_covered     = $_POST['service_covered'];
$apply_gst           = isset($_POST['apply_gst']) ? 1 : 0;
$billing_address     = $_POST['billing_address'] ?? '';
$shipping_address    = $_POST['shipping_address'] ?? '';
$gst_invoice_no      = $_POST['gst_invoice_no'] ?? '';

// Calculate GST
$gst_amount = $apply_gst ? $total_amount * 0.18 : 0;
$total_incl_gst = $total_amount + $gst_amount;

// Insert into tbl_client
$query = "INSERT INTO tbl_client 
(cust_name, cust_phone, cust_email, cust_address, service, service_date, service_term_condition, total_amount, gst_amount, warranty, service_covered, inquiry_id, apply_gst, billing_address, shipping_address, gst_invoice_no)
VALUES 
(
    '{$inq['name']}',
    '{$inq['phone']}',
    '{$inq['email']}',
    '{$inq['address']}',
    '$service',
    '$service_date',
    '$service_tc',
    '$total_amount',
    '$gst_amount',
    '$warranty',
    '$service_covered',
    '$id',
    '$apply_gst',
    '$billing_address',
    '$shipping_address',
    '$gst_invoice_no'
)";

if(mysqli_query($conn, $query)){
    $client_id = mysqli_insert_id($conn);
    $paymentQuery = "INSERT INTO tbl_payment (client_id, total_amount, due_date) VALUES ('$client_id', '$total_incl_gst', '$service_date')";
    mysqli_query($conn, $paymentQuery);

    $_SESSION['status'] = "Client Added Successfully!";
    header("Location: view-client.php");
    exit();
} else {
    $_SESSION['status'] = "Failed to Add Client!";
    header("Location: service-done.php?id=$id");
    exit();
}
?>
