File "addCustomerBookingDone.php"

Full Path: /home/chawlag2/public_html/cars/admin/vendor/jquery/addCustomerBookingDone.php
File size: 8.94 KB
MIME-type: text/x-php
Charset: utf-8

<?php
session_start();
include('admin/dbconn.php');

date_default_timezone_set("Asia/Karachi");
$dateAdded = date('Y-m-d');
$timeStamp = date('Y-m-d H:i:s');

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
  http_response_code(405);
  exit("Method Not Allowed");
}

/* ---------------- Helpers ---------------- */
function clean($v) {
  $v = trim((string)$v);
  return $v;
}
function esc($v) {
  return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

/* ---------------- Collect + Validate ---------------- */
$fullname      = clean($_POST['fullname'] ?? '');
$guardian      = clean($_POST['guardian'] ?? '');
$variant       = clean($_POST['variant'] ?? '');
$color         = clean($_POST['color'] ?? '');
$interiorColor = clean($_POST['interiorColor'] ?? '');
$userEmail     = clean($_POST['email'] ?? '');
$password      = clean($_POST['password'] ?? '');
$dob           = clean($_POST['dob'] ?? '');
$contactNo     = clean($_POST['contactNo'] ?? '');
$country       = clean($_POST['country'] ?? '');
$city          = clean($_POST['city'] ?? '');
$cnic          = clean($_POST['cnic'] ?? '');
$address       = clean($_POST['address'] ?? '');

$errors = [];
if ($fullname === '') $errors[] = "Full name is required";
if ($guardian === '') $errors[] = "Father/Husband is required";
if ($variant === '') $errors[] = "Variant is required";
if ($color === '') $errors[] = "Exterior color is required";
if ($interiorColor === '') $errors[] = "Interior color is required";
if ($userEmail === '' || !filter_var($userEmail, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email is required";
if ($password === '') $errors[] = "Password is required";
if ($dob === '') $errors[] = "DOB is required";
if ($contactNo === '') $errors[] = "Contact No is required";
if ($country === '') $errors[] = "Country is required";
if ($city === '') $errors[] = "City is required";
if ($cnic === '') $errors[] = "CNIC/NTN is required";
if ($address === '') $errors[] = "Address is required";

if (!isset($_FILES['image1ToUpload']) || $_FILES['image1ToUpload']['error'] !== UPLOAD_ERR_OK) {
  $errors[] = "CNIC Front is required";
}
if (!isset($_FILES['image2ToUpload']) || $_FILES['image2ToUpload']['error'] !== UPLOAD_ERR_OK) {
  $errors[] = "CNIC Back is required";
}

if (!empty($errors)) {
  echo "<script>alert('Please fix:\\n- " . esc(implode("\\n- ", $errors)) . "');history.back();</script>";
  exit;
}

// Make names pretty
$fullnamePretty = mb_convert_case($fullname, MB_CASE_TITLE, "UTF-8");
$guardianPretty = mb_convert_case($guardian, MB_CASE_TITLE, "UTF-8");
$cityPretty     = mb_convert_case($city, MB_CASE_TITLE, "UTF-8");

/* ---------------- Upload Files Safely ---------------- */
$uploadDir = __DIR__ . "/images/customers/";
if (!is_dir($uploadDir)) {
  @mkdir($uploadDir, 0755, true);
}

$allowedExt = ['jpg','jpeg','png','pdf'];
$maxSize = 8 * 1024 * 1024; // 8MB

function uploadFile($fileKey, $uploadDir, $allowedExt, $maxSize) {
  $file = $_FILES[$fileKey];

  if ($file['size'] > $maxSize) {
    throw new Exception("File too large: " . $fileKey);
  }

  $originalName = $file['name'];
  $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

  if (!in_array($ext, $allowedExt)) {
    throw new Exception("Invalid file type for: " . $fileKey);
  }

  // unique name
  $newName = uniqid($fileKey . "_", true) . "." . $ext;
  $targetPath = $uploadDir . $newName;

  if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
    throw new Exception("Upload failed for: " . $fileKey);
  }

  // return DB path (relative)
  return "images/customers/" . $newName;
}

try {
  $dbfile1 = uploadFile("image1ToUpload", $uploadDir, $allowedExt, $maxSize);
  $dbfile2 = uploadFile("image2ToUpload", $uploadDir, $allowedExt, $maxSize);
} catch (Exception $e) {
  echo "<script>alert('Upload error: " . esc($e->getMessage()) . "');history.back();</script>";
  exit;
}

/* ---------------- Save in DB using Prepared Statement ---------------- */
// IMPORTANT: store password securely
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

$sql = "INSERT INTO customers
(customerName, fatherHusbandName, address, nicNo, contactNo, email, password, dob, country, city, variant, exteriorColor, interiorColor, nicFront, nicBack, status, dateAdded, timeStamp)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

$stmt = $conn->prepare($sql);
if (!$stmt) {
  echo "<script>alert('Database error: unable to prepare query');history.back();</script>";
  exit;
}

$status = "0";
$stmt->bind_param(
  "ssssssssssssssssss",
  $fullnamePretty,
  $guardianPretty,
  $address,
  $cnic,
  $contactNo,
  $userEmail,
  $hashedPassword,
  $dob,
  $country,
  $city,
  $variant,
  $color,
  $interiorColor,
  $dbfile1,
  $dbfile2,
  $status,
  $dateAdded,
  $timeStamp
);

if (!$stmt->execute()) {
  echo "<script>alert('Database error: unable to save record');history.back();</script>";
  exit;
}
$stmt->close();

/* ---------------- Email Setup ---------------- */
$logoUrl = "https://chawlagreenmotors.com/images/logo2.png";

$fromEmail = "info@chawlagreenmotors.com";
$fromName  = "Chawla Green Motors";

$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type:text/html;charset=UTF-8\r\n";
$headers .= "From: {$fromName} <{$fromEmail}>\r\n";
$headers .= "Reply-To: {$fromName} <{$fromEmail}>\r\n";
$headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";

/* ---------------- Admin Email ---------------- */
$adminRecipients = [
  "info@chawlagreenmotors.com",
  "syedzeeshanali38@gmail.com",
  "sabih-hassan@hotmail.com"
];

$adminSubject = "New Order Received!";

$adminMsg = "
<html><head><meta charset='UTF-8'></head>
<body style='font-family:Arial,sans-serif;'>
  <div style='max-width:720px;margin:0 auto;'>
    <div style='text-align:center;padding:10px 0;'>
      <img src='{$logoUrl}' width='140' alt='Chawla Green Motors'>
    </div>

    <h2 style='margin:10px 0;color:#111;'>New booking/order received</h2>
    <table cellpadding='8' cellspacing='0' border='1' style='border-collapse:collapse;width:100%;'>
      <tr><td><b>Name</b></td><td>".esc($fullnamePretty)."</td></tr>
      <tr><td><b>Father/Husband</b></td><td>".esc($guardianPretty)."</td></tr>
      <tr><td><b>Email</b></td><td>".esc($userEmail)."</td></tr>
      <tr><td><b>Contact No</b></td><td>".esc($contactNo)."</td></tr>
      <tr><td><b>CNIC/NTN</b></td><td>".esc($cnic)."</td></tr>
      <tr><td><b>Address</b></td><td>".esc($address)."</td></tr>
      <tr><td><b>City</b></td><td>".esc($cityPretty)."</td></tr>
      <tr><td><b>Variant</b></td><td>".esc($variant)."</td></tr>
      <tr><td><b>Exterior Color</b></td><td>".esc($color)."</td></tr>
      <tr><td><b>Interior Color</b></td><td>".esc($interiorColor)."</td></tr>
      <tr><td><b>CNIC Front</b></td><td>".esc($dbfile1)."</td></tr>
      <tr><td><b>CNIC Back</b></td><td>".esc($dbfile2)."</td></tr>
    </table>

    <p style='margin-top:18px;color:#333;'>
      Regards,<br><b>Chawla Green Motors</b>
    </p>
  </div>
</body></html>
";

$adminSent = true;
foreach ($adminRecipients as $to) {
  if (!mail($to, $adminSubject, $adminMsg, $headers)) {
    $adminSent = false;
  }
}

/* ---------------- User Confirmation Email ---------------- */
$userSubject = "Booking request received - Chawla Green Motors";

$userMsg = "
<html><head><meta charset='UTF-8'></head>
<body style='font-family:Arial,sans-serif;'>
  <div style='max-width:720px;margin:0 auto;'>
    <div style='text-align:center;padding:10px 0;'>
      <img src='{$logoUrl}' width='140' alt='Chawla Green Motors'>
    </div>

    <h2 style='margin:10px 0;color:#111;'>Thank you!</h2>

    <p style='color:#333;line-height:1.6;'>
      Dear ".esc($fullnamePretty).",<br><br>
      Thank you for your interest in our product.<br>
      Your booking request has been received successfully.<br><br>
      <b>Your details:</b><br>
      Variant: ".esc($variant)."<br>
      Exterior Color: ".esc($color)."<br>
      Interior Color: ".esc($interiorColor)."<br>
      City: ".esc($cityPretty)."<br><br>
      We have received your CNIC pictures as well. Our representative will contact you shortly.
    </p>

    <p style='color:#333;'>
      Regards,<br><b>Chawla Green Motors</b><br>
      Phone: +92 311 4995162<br>
      Email: info@chawlagreenmotors.com
    </p>
  </div>
</body></html>
";

$userSent = mail($userEmail, $userSubject, $userMsg, $headers);

/* ---------------- Response ---------------- */
if ($adminSent) {
  echo "<script>alert('Thank you! Your booking request has been received."
    . ($userSent ? " A confirmation email has been sent to your email." : " Confirmation email could not be sent right now.")
    . "');</script>";
  echo "<script>window.location.href='index.html';</script>";
  exit;
} else {
  echo "<script>alert('Sorry! We could not submit your request right now. Please try again later.');</script>";
  echo "<script>history.back();</script>";
  exit;
}
?>