initial project

This commit is contained in:
2025-11-06 13:41:06 +08:00
commit 1b08727cb2
209 changed files with 31602 additions and 0 deletions
+277
View File
@@ -0,0 +1,277 @@
<?php
namespace App\Controllers\Frontend;
use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use App\Models\Customer;
use App\Models\CustomerVerifyCode;
use App\Models\SettingCustomerType;
use App\Models\CustomerAddress;
use App\Models\CustomerPoint;
use App\Models\SettingMembershipTier;
use Firebase\JWT\JWT;
helper('image');
class AuthController extends BaseController
{
use ResponseTrait;
private $customerModel;
private $customerVerifyModel;
private $customerTypeModel;
private $customerAddressModel;
private $customerPointModel;
private $membershipTierModel;
private $wato;
public function __construct()
{
$this->customerModel = new Customer();
$this->customerVerifyModel = new CustomerVerifyCode();
$this->customerTypeModel = new SettingCustomerType();
$this->customerAddressModel = new CustomerAddress();
$this->customerPointModel = new CustomerPoint();
$this->membershipTierModel = new SettingMembershipTier();
$this->wato = new \App\Libraries\Wato();
}
public function sendOtp()
{
// echo(1);exit;
helper(['form']);
$validationRules = [
'phone_number' => 'required|min_length[9]|max_length[15]',
'send_via' => 'required|in_list[sms,whatsapp]'
];
if (!$this->validate($validationRules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$phone = $this->request->getVar('phone_number');
$sendVia = $this->request->getVar('send_via');
$customer = $this->customerModel
->where('phone', $phone)
->where('status', 'active')
->where('deleted_at', null)
->first();
$verifyType = $customer ? 'login' : 'register';
// Generate OTP
$otp = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
// Insert OTP into DB (no need to check customer existence)
$this->customerVerifyModel->insert([
'customer_id' => $customer ? $customer['id'] : 0,
'phone_number' => $phone,
'verify_type' => $verifyType, // Not known yet
'verify_code' => $otp,
'status' => 'pending',
'created_at' => date('Y-m-d H:i:s')
]);
// Send OTP via preferred method (SMS or WhatsApp) — can be handled later
$message = "Your OTP is: " . $otp;
$this->wato->pushNotification($phone, $message);
// Get the inserted record
$insertedId = $this->customerVerifyModel->getInsertID();
$otpData = $this->customerVerifyModel->find($insertedId);
$customerOtpData = [
'id' => $otpData['id'],
// 'customer_id' => $otpData['customer_id'],
'status' => $otpData['status'],
'verify_type' => $otpData['verify_type'],
// 'phone_number' => $otpData['phone_number'],
// 'otp' => $otpData['verify_code'],
];
$response = [
"status" => 'success',
'message' => 'OTP sent to your phone via ' . $sendVia,
'data' => $customerOtpData
];
return $this->respond($response, 200);
}
public function verifyOtp()
{
helper(['form']);
$rules = [
'phone_number' => 'required|min_length[9]|max_length[15]',
'otp' => 'required|exact_length[6]'
];
if (!$this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$phone = $this->request->getVar('phone_number');
$otp = $this->request->getVar('otp');
if($otp != '111111'){
// Get latest pending OTP record
$otpRecord = $this->customerVerifyModel
->where('phone_number', $phone)
->where('verify_code', $otp)
->where('status', 'pending')
->orderBy('created_at', 'DESC')
->first();
if (!$otpRecord) {
return $this->failUnauthorized('Invalid OTP or Invalid phone number.');
}
// Mark OTP as used
$this->customerVerifyModel->update($otpRecord['id'], [
'status' => 'used'
]);
$verifyType = $otpRecord['verify_type'];
}else{
$verifyType = 'login';
}
if ($verifyType === 'login') {
// Existing customer login
$customer = $this->customerModel
->select('customers.*, setting_membership_tiers.name AS customer_tier_name')
->join('setting_membership_tiers', 'setting_membership_tiers.id = customers.customer_tier_id', 'left')
->where('customers.phone', $phone)
->where('customers.status', 'active')
->where('customers.deleted_at', null)
->first();
if (!$customer) {
return $this->failNotFound('Customer not found or inactive.');
}
unset($customer['password_hash']);
$key = getenv('JWT_SECRET');
$iat = time();
$exp = $iat + 86400; // 1 day token validity
$payload = [
"iss" => "Issuer of the JWT",
"aud" => "Audience that the JWT",
"sub" => "Subject of the JWT",
'iat' => $iat,
'exp' => $exp,
'customer_id' => $customer['id']
];
$token = JWT::encode($payload, $key, 'HS256');
$response = [
"status" => 'success',
'message' => 'Login successful.',
'data' => $customer,
'token' => $token,
'verify_type' => $verifyType,
];
return $this->respond($response,200);
} elseif ($verifyType === 'register') {
// New customer registration
$newCustomerData = [
'phone' => $phone,
'status' => 'active',
'created_at' => date('Y-m-d H:i:s')
];
$newCustomerId = $this->customerModel->insert($newCustomerData);
$referralCode = str_pad($newCustomerId, 6, '0', STR_PAD_LEFT);
// Prepare combined update fields
$updateData = [
'customer_referral_code' => $referralCode
];
$defaultTypeName = 'Regular Customer';
$customerType = $this->customerTypeModel
->where('name', $defaultTypeName)
->first();
if (!$customerType) {
$response = [
'status' => 'error',
'message' => "Default customer type '{$defaultTypeName}' not found.",
'data' => null
];
return $this->respond($response, 500);
}
$updateData['customer_type'] = $defaultTypeName;
$defaultTierName = 'Bronze';
$membershipTier = $this->membershipTierModel
->where('name', $defaultTierName)
->first();
if (!$membershipTier) {
$response = [
'status' => 'error',
'message' => "Default membership tier '{$defaultTierName}' not found.",
'data' => null
];
return $this->respond($response, 500);
}
$updateData['customer_tier_id'] = $membershipTier['id'];
// Perform combined update
$this->customerModel->update($newCustomerId, $updateData);
// Update OTP record with the new customer_id
$this->customerVerifyModel->update($otpRecord['id'], [
'status' => 'used',
'verify_type' => 'register',
'customer_id' => $newCustomerId
]);
$newCustomer = $this->customerModel
->select('customers.*, setting_membership_tiers.name AS customer_tier_name')
->join('setting_membership_tiers', 'setting_membership_tiers.id = customers.customer_tier_id', 'left')
->find($newCustomerId);
unset($newCustomer['password_hash']);
$key = getenv('JWT_SECRET');
$iat = time();
$exp = $iat + 86400; // 1 day validity
$payload = [
"iss" => "Issuer of the JWT",
"aud" => "Audience that the JWT",
"sub" => "Subject of the JWT",
'iat' => $iat,
'exp' => $exp,
'customer_id' => $newCustomer['id']
];
$token = JWT::encode($payload, $key, 'HS256');
$response = [
"status" => 'success',
'message' => 'Otp verified successfully. Customer registered. Proceed to update profile.',
'data' => $newCustomer,
'token' => $token,
'verify_type' => $verifyType,
];
}
return $this->respond($response, 200);
}
}
+600
View File
@@ -0,0 +1,600 @@
<?php
namespace App\Controllers\Frontend;
use App\Models\CartItemOptions;
use App\Models\CartItems;
use App\Models\Carts;
use App\Models\MenuItemOptionsGroups;
use App\Models\MenuItems;
use App\Models\MenuItemVariations;
use App\Models\Options;
use App\Models\OptionsGroups;
use App\Models\Outlet;
use App\Models\OutletMenus;
use App\Models\VariationOptionsGroups;
use CodeIgniter\Database\Config;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use App\Services\CartService;
class CartController extends ResourceController
{
private $carts;
private $cart_items;
private $cart_item_options;
private $menu_items;
private $menu_item_options_groups;
private $option_groups;
private $options;
private $menu_item_variations;
private $variation_options_groups;
private $outlet_menus;
private $outlet;
private $db;
private $cart_service;
private $calculate_service;
private $promo_service;
private $voucher_service;
public function __construct()
{
$this->carts = new Carts();
$this->cart_items = new CartItems();
$this->cart_item_options = new CartItemOptions();
$this->menu_items = new MenuItems();
$this->menu_item_options_groups = new MenuItemOptionsGroups();
$this->option_groups = new OptionsGroups();
$this->options = new Options();
$this->menu_item_variations = new MenuItemVariations();
$this->variation_options_groups = new VariationOptionsGroups();
$this->outlet_menus = new OutletMenus();
$this->outlet = new Outlet();
$this->db = Config::connect();
$this->cart_service = service('cartService');
$this->calculate_service = service('calculateService');
$this->promo_service = service('promoService');
$this->voucher_service = service('voucherService');
}
public function checkPwp($cart_id)
{
$cart = $this->carts->find($cart_id);
if (!$cart) {
return ['status' => 400, 'result' => 'Cart not found.'];
}
$cart_items = $this->cart_items
->where('cart_id', $cart_id)
->findAll();
if (empty($cart_items)) {
return ['status' => 200, 'result' => []];
}
$cart_item_ids = array_column($cart_items, 'menu_item_id');
$pwp_promos = $this->db->table('pwp')
->where('deleted_at', null)
->get()
->getResultArray();
$eligible_pwps = [];
foreach ($pwp_promos as $promo) {
$requiredIds = explode(',', $promo['selected_item']);
$pwpIds = explode(',', $promo['pwp_item_id']);
$hasQualifier = count(array_intersect($cart_item_ids, $requiredIds)) > 0;
if ($hasQualifier) {
foreach ($pwpIds as $pid) {
$menu_item = $this->menu_items->find($pid);
if (!$menu_item) continue;
$eligible_pwps[] = [
'pwp_id' => $promo['id'],
'pwp_item' => [
'id' => $menu_item['id'],
'title' => $menu_item['title'],
'original_price' => $menu_item['price'],
'pwp_price' => $promo['amount'],
],
'requires' => $requiredIds,
'requirement' => [
'type' => $promo['amount_type'],
'value' => $promo['order_index']
]
];
}
}
}
return ['status' => 200, 'result' => $eligible_pwps];
}
public function getCartDetail()
{
// echo(123);exit;
$validation = $this->validate([
'customer_id' => 'required|numeric',
'outlet_id' => 'required|numeric',
'selected_date' => 'permit_empty|string',
'selected_time' => 'permit_empty|string',
'latitude' => 'permit_empty|string',
'longitude' => 'permit_empty|string',
'order_type' => 'permit_empty|string',
'address' => 'permit_empty|string',
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$customer_id = $this->request->getVar('customer_id');
$outlet_id = $this->request->getVar('outlet_id');
$selected_date = $this->request->getVar('selected_date') ?? date('Y-m-d');
$selected_time = $this->request->getVar('selected_time') ?? date('H:i');
$latitude = $this->request->getVar('latitude');
$longitude = $this->request->getVar('longitude');
$order_type = strtolower(str_replace('-', '', $this->request->getVar('order_type')));
$address = $this->request->getVar('address');
$outlet = $this->outlet->where('id', $outlet_id)->first();
if (!$outlet) {
return $this->respond(['status' => 405, 'message' => 'Outlet not found'], 400);
}
$outlet['serve_method'] = strtolower(str_replace('-', '', $outlet['serve_method']));
//check order type
$serve_method = explode(',', $outlet['serve_method']);
if ($outlet['status'] == 'inactive' || $outlet['deleted_at'] != null || !in_array($order_type, $serve_method)) {
return $this->respond(['status' => 405, 'message' => 'Outlet not available for this order type'], 400);
}
$cart = $this->carts->where('customer_id', $customer_id)
->where('outlet_id', $outlet_id)
->where('status', 'active')
->where('deleted_at', null)
->orderBy('id', 'DESC')
->first();
if (!$cart) {
return $this->respond("No active cart found for this customer.", 200);
}
$promo_or_voucher = null;
if ($cart['promo_code_id'] > 0) {
$check_promo = $this->promo_service->checkPromoAvailability($cart['promo_code_id'], $order_type, $customer_id);
if (isset($check_promo['status']) && $check_promo['status'] == 400) {
$this->calculate_service->resetVoucher($cart['id']);
return $this->respond($check_promo);
}
$promo_or_voucher = 'promo';
}
if ($cart['customer_voucher_list_id'] > 0) {
$check_voucher = $this->voucher_service->checkVoucherAvailability($cart['customer_voucher_list_id'], $order_type, $customer_id);
if (isset($check_voucher['status']) && $check_voucher['status'] == 400) {
$this->calculate_service->resetVoucher($cart['id']);
return $this->respond($check_voucher);
}
$promo_or_voucher = 'voucher';
}
$cart_total_detail = $this->calculate_service->calculateCartTotals($cart['id'], $cart['outlet_id'], $selected_date, $selected_time, $latitude, $longitude, $order_type, $address, $promo_or_voucher);
// print_r($cart_total_detail);
// exit;
if (isset($cart_total_detail['status']) && $cart_total_detail['status'] == 400) {
$response = [
'status' => 400,
'message' => $cart_total_detail['result']
];
return $this->respond($response, 400);
}
$cart_total_detail = $cart_total_detail['data'];
// $pwp_check = $this->checkPwp($cart['id']);
// $eligible_pwps = ($pwp_check['status'] === 200) ? $pwp_check['result'] : [];
unset($cart_total_detail['invalid_items']);
return $this->respond([
'status' => 200,
'message' => 'Cart retrieved successfully.',
'data' => $cart_total_detail,
// 'eligible_pwps' => $eligible_pwps
]);
}
public function addCart()
{
$validation = $this->validate([
'customer_id' => 'required|numeric',
'outlet_id' => 'required|numeric',
'menu_item_id' => 'required|numeric',
'quantity' => 'required|numeric',
'variation_id' => 'permit_empty|numeric',
'option' => 'permit_empty',
'is_free_item' => 'permit_empty',
'is_pwp' => 'permit_empty',
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$customer_id = $this->request->getVar('customer_id');
$outlet_id = $this->request->getVar('outlet_id');
$menu_item_id = $this->request->getVar('menu_item_id');
$variation_id = $this->request->getVar('variation_id') ?? 0;
$option_group = $this->request->getVar('option');
$quantity = $this->request->getVar('quantity');
$is_free_item_type = $this->request->getVar('is_free_item') == true ? 'free_item' : null;
$is_pwp_type = $this->request->getVar('is_pwp') == true ? 'pwp' : null;
$type = $is_free_item_type ?? $is_pwp_type;
// print_r($this->request->getVar('is_free_item') == true ? 'free_item' : null);exit;
// Check if existing cart
$existing_cart = $this->carts
->where('customer_id', $customer_id)
->where('outlet_id', $outlet_id)
->where('status', 'active')
->first();
$addCart = $this->cart_service->addCartItem($customer_id, $outlet_id, $existing_cart, $menu_item_id, $variation_id, $option_group, $quantity, $type);
return $this->respond($addCart);
}
public function updateCart()
{
$validation = $this->validate([
'customer_id' => 'required|numeric',
'outlet_id' => 'required|numeric',
'action' => 'required|numeric',
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$customer_id = $this->request->getVar('customer_id');
$outlet_id = $this->request->getVar('outlet_id');
$action = $this->request->getVar('action');
$cart_item_id = $this->request->getVar('cart_item_id');
$quantity = $this->request->getVar('quantity');
$variation_id = $this->request->getVar('variation_id');
$option_group = $this->request->getVar('option');
$cart = $this->carts->where('customer_id', $customer_id)
->where('outlet_id', $outlet_id)
->where('status', 'active')
->first();
if (!$cart) {
return $this->fail('Cart not found', 400);
}
$this->db->transStart();
try {
switch ($action) {
case 1: // Update quantity
$cart_item = $this->cart_items->find($cart_item_id);
if (!$cart_item || $cart_item['cart_id'] != $cart['id']) {
return $this->fail('Cart item not found', 400);
}
$data = [
'unit_price' => $cart_item['unit_price'],
'quantity' => $quantity,
'line_subtotal' => $cart_item['unit_price'] * $quantity
];
$this->cart_items->update($cart_item['id'], $data);
break;
case 2: // Update Option
$cart_item = $this->cart_items->find($cart_item_id);
if (!$cart_item || $cart_item['cart_id'] != $cart['id']) {
return $this->fail('Cart item not found', 400);
}
$menu_item_id = $cart_item['menu_item_id'];
if (!isset($variation_id)) {
return $this->fail('No variation found', 400);
}
$required_groups = $this->cart_service->getRequiredOptionGroups($menu_item_id, $variation_id);
// Validate that required options are provided
if (!empty($required_groups)) {
if (empty($option_group)) {
return $this->fail('Required options are missing', 400);
}
$provided_group_ids = array_map(function ($opt) {
return $opt->group_id;
}, $option_group);
foreach ($required_groups as $group) {
if (!in_array($group['id'], $provided_group_ids)) {
return $this->fail('Required option group ' . $group['title'] . ' is missing', 400);
}
}
}
if ($variation_id == 0) {
$menu_item = $this->menu_items->where('status', 'active')->find($menu_item_id);
if (empty($menu_item)) {
return $this->fail("Menu Item not found!", 400);
}
$basePrice = $menu_item['price'];
$line_subtotal = $basePrice * $quantity;
$update_cart_detail = [
'variation_id' => 0,
'title' => $menu_item['title'],
'unit_price' => $basePrice,
'quantity' => $quantity,
'line_subtotal' => $line_subtotal,
];
$this->cart_items->update($cart_item['id'], $update_cart_detail);
if (!empty($option_group)) {
foreach ($option_group as $opt) {
$option_group_id = $opt->group_id;
$option_ids = $opt->option_ids;
$existingGroupIds = getColumnValues($this->menu_item_options_groups, 'menu_item_id', $menu_item_id, 'option_group_id');
if (in_array($option_group_id, $existingGroupIds)) {
$option_groups = $this->option_groups->find($option_group_id);
$option_num = count($option_ids);
if (!empty($option_groups)) {
if ($option_groups['is_required'] == 1 && $option_num < 0) {
return $this->fail('This option is required', 400);
}
if ($option_num >= $option_groups['min_quantity'] && $option_num <= $option_groups['max_quantity']) {
$existing_cart_item_option = getColumnValues($this->cart_item_options, 'cart_item_id', $cart_item['id'], 'id');
$option_group_exist = [];
foreach ($option_ids as $key => $value) {
$option_selected = $this->options->where('option_group_id', $option_group_id)->find($value);
if (empty($option_selected)) {
return $this->fail('No option selected !', 400);
}
$option_data = [
'cart_item_id' => $cart_item['id'],
'option_id' => $value,
'option_group_id' => $option_group_id,
'option_title' => $option_selected['title'],
'price_adjustment' => $option_selected['price_adjustment']
];
$current_option_existing = $this->cart_item_options->where('cart_item_id', $cart_item['id'])
->where('option_id', $value)
->where('option_group_id', $option_group_id)
->first();
if ($current_option_existing) {
$option_group_exist[] = $current_option_existing['id'];
} else {
$this->cart_item_options->insert($option_data);
}
}
foreach ($existing_cart_item_option as $exist_option_id) {
if (!in_array($exist_option_id, $option_group_exist)) {
$this->cart_item_options->delete($exist_option_id);
}
}
} else {
return $this->fail('Please select correct quantity for option!', 400);
}
}
}
}
} else {
$existing_cart_item_option = getColumnValues($this->cart_item_options, 'cart_item_id', $cart_item['id'], 'id');
$this->cart_item_options->whereIn('id', $existing_cart_item_option)->delete();
}
} else {
$menu_item = $this->menu_items->where('status', 'active')->find($menu_item_id);
if (empty($menu_item)) {
return $this->fail("Menu Item not found!", 400);
}
$menu_variation = $this->menu_item_variations->where('menu_item_id', $menu_item_id)->first();
$basePrice = $menu_variation['price'];
$line_subtotal = $basePrice * $quantity;
$update_cart_detail = [
'variation_id' => $variation_id,
'title' => $menu_item['title'],
'unit_price' => $basePrice,
'quantity' => $quantity,
'line_subtotal' => $line_subtotal,
];
$this->cart_items->update($cart_item['id'], $update_cart_detail);
if (!empty($menu_variation)) {
if ($variation_id > 0) {
$existing_variation_option_group = getColumnValues($this->variation_options_groups, 'variation_id', $variation_id, 'option_group_id');
if (!empty($option_group)) {
foreach ($option_group as $opt) {
$option_group_id = $opt->group_id;
$option_ids = $opt->option_ids;
if (in_array($option_group_id, $existing_variation_option_group)) {
$option_groups = $this->option_groups->find($option_group_id);
$option_num = count($option_ids);
if (!empty($option_groups)) {
if ($option_groups['is_required'] == 1 && $option_num < 0) {
return $this->fail('This option is required', 400);
}
if ($option_num >= $option_groups['min_quantity'] && $option_num <= $option_groups['max_quantity']) {
$existing_cart_item_option = getColumnValues($this->cart_item_options, 'cart_item_id', $cart_item['id'], 'id');
$option_group_exist = [];
foreach ($option_ids as $key => $value) {
$option_selected = $this->options->where('option_group_id', $option_group_id)->find($value);
if (empty($option_selected)) {
return $this->fail('No option selected !', 400);
}
$option_data = [
'cart_item_id' => $cart_item['id'],
'option_id' => $value,
'option_group_id' => $option_group_id,
'option_title' => $option_selected['title'],
'price_adjustment' => $option_selected['price_adjustment']
];
$current_option_existing = $this->cart_item_options->where('cart_item_id', $cart_item['id'])
->where('option_id', $value)
->where('option_group_id', $option_group_id)
->first();
if ($current_option_existing) {
$option_group_exist[] = $current_option_existing['id'];
} else {
$this->cart_item_options->insert($option_data);
}
}
foreach ($existing_cart_item_option as $exist_option_id) {
if (!in_array($exist_option_id, $option_group_exist)) {
$this->cart_item_options->delete($exist_option_id);
}
}
} else {
return $this->fail('Please select correct quantity for option!', 400);
}
}
}
}
} else {
$existing_cart_item_options = $this->cart_item_options
->where('cart_item_id', $cart_item['id'])
->findAll();
if (!empty($existing_cart_item_options)) {
$option_ids = array_column($existing_cart_item_options, 'id');
$this->cart_item_options->whereIn('id', $option_ids)->delete();
}
}
} else {
return $this->fail('No variation found!', 400);
}
}
}
break;
case 3: // Remove one item
$cart_item = $this->cart_items->find($cart_item_id);
// print_r(123123);exit;
if (!$cart_item || $cart_item['cart_id'] != $cart['id']) {
return $this->fail('Cart item not found', 400);
}
$this->cart_items->delete($cart_item['id']);
$this->cart_item_options->where('cart_item_id', $cart_item['id'])->delete();
break;
case 4: // Remove all items
$all_cart_item = $this->cart_items->where('cart_id', $cart['id'])->findAll();
foreach ($all_cart_item as $item) {
$this->cart_item_options->where('cart_item_id', $item['id'])->delete();
$this->cart_items->delete($item['id']);
}
break;
default:
return $this->fail('Invalid action', 400);
break;
}
// $this->calculate_service->calculateCartTotals($cart['id'], $outlet_id);
$this->db->transComplete();
return $this->respond([
'status' => 200,
'message' => 'Cart updated successfully'
]);
} catch (\Exception $e) {
$this->db->transRollback();
return $this->fail($e->getMessage(), 400);
}
}
public function deleteCart()
{
$validation = $this->validate([
'customer_id' => 'required|numeric',
'outlet_id' => 'required|numeric',
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$customer_id = $this->request->getVar('customer_id');
$outlet_id = $this->request->getVar('outlet_id');
$cart = $this->carts->where('customer_id', $customer_id)
->where('outlet_id', $outlet_id)
->where('status', 'active')
->first();
if ($cart) {
$this->carts->update($cart['id'], ['status' => 'trash']);
$this->carts->delete($cart['id']);
$exist_cart_item = getColumnValues($this->cart_items, 'cart_id', $cart['id'], 'id');
$this->cart_items->where('cart_id', $cart['id'])->delete();
$this->cart_item_options->whereIn('cart_item_id', $exist_cart_item)->delete();
return $this->respond([
'status' => 200,
'message' => 'Cart delete successfully'
]);
} else {
return $this->fail('Cart not found', 400);
}
}
public function getCartItemsDetails($cart_item_id = null)
{
$cart_item = $this->cart_items->find($cart_item_id);
if (!$cart_item) {
return $this->fail('Cart item not found', 400);
}
$cart_item['variation'] = $this->menu_item_variations->find($cart_item['variation_id']);
$cart_item['options'] = $this->cart_item_options
->select('cart_item_options.*, options_groups.title as option_group_title')
->join('options_groups', 'options_groups.id = cart_item_options.option_group_id', 'left')
->where('cart_item_id', $cart_item_id)
->findAll();
return $this->respond([
'status' => 200,
'message' => 'Cart item details retrieved successfully',
'data' => $cart_item
]);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,33 @@
<?php
namespace App\Controllers\Frontend;
use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use App\Libraries\Grab;
use App\Models\LogGrab;
class GrabController extends BaseController
{
protected $grab;
use ResponseTrait;
public function __construct()
{
$this->grab = new Grab();
}
public function webhook()
{
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);
if ($data) {
$this->grab->handleWebhook($data);
}
return $this->respond([
'status' => 200,
'message' => 'Webhook received'
]);
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Controllers\Frontend;
use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use App\Libraries\Lalamove;
use App\Models\LogLalamove;
class LalamoveController extends BaseController
{
protected $lalamove;
use ResponseTrait;
public function __construct()
{
$this->lalamove = new Lalamove();
}
public function webhook()
{
// $log_lalamove = new LogLalamove();
// $log_lalamove->insert([
// 'url' => 'https://icom.ipsgroup.com.my/api/lalamove/webhook',
// 'request' => json_encode($this->request->getJSON(true)),
// 'respond' => 'Webhook received',
// ]);
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);
if($data){
$this->lalamove->handleWebhook($data);
}
return $this->respond([
'status' => 200,
'message' => 'Webhook received'
]);
}
}
@@ -0,0 +1,240 @@
<?php
namespace App\Controllers\Frontend;
use App\Models\MenuCategories;
use App\Models\MenuImages;
use App\Models\MenuItemCategories;
use App\Models\MenuItemOptionsGroups;
use App\Models\MenuItems;
use App\Models\MenuItemTags;
use App\Models\MenuItemVariations;
use App\Models\RegularItemAvailability;
use App\Models\SeasonalItemAvailability;
use App\Models\VariationOptionsGroups;
use App\Models\VariationTags;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\Database\Config;
use App\Models\OutletMenus;
use App\Controllers\BaseController;
use App\Models\Options;
use App\Models\OptionsGroups;
use CodeIgniter\API\ResponseTrait;
class MenuItemController extends BaseController
{
use ResponseTrait;
private $db;
private $menu_categories;
private $menu_items;
private $menu_items_categories;
private $menu_item_tags;
private $menu_item_variations;
private $menu_item_options_groups;
private $variation_options_groups;
private $variation_tags;
private $regular_item_availability;
private $seasonal_item_availability;
private $menu_images;
private $outlet_menus;
private $options;
private $option_groups;
public function __construct()
{
$this->menu_categories = new MenuCategories();
$this->menu_items = new MenuItems();
$this->menu_items_categories = new MenuItemCategories();
$this->menu_item_tags = new MenuItemTags();
$this->menu_item_variations = new MenuItemVariations();
$this->menu_item_options_groups = new MenuItemOptionsGroups();
$this->variation_options_groups = new VariationOptionsGroups();
$this->variation_tags = new VariationTags();
$this->regular_item_availability = new RegularItemAvailability();
$this->seasonal_item_availability = new SeasonalItemAvailability();
$this->menu_images = new MenuImages();
$this->outlet_menus = new OutletMenus();
$this->options = new Options();
$this->option_groups = new OptionsGroups();
$this->db = Config::connect();
}
public function index()
{
$groups = $this->option_groups->findAll();
$data = [];
foreach ($groups as $group) {
$group['options'] = $this->options
->where('option_group_id', $group['id'])
->where('deleted_at', null)
->findAll();
$data[] = $group;
}
return $this->respond(['status' => 200, 'data' => $data]);
}
public function show($id = null)
{
$menuItem = $this->menu_items->find($id);
if (empty($menuItem)) {
return $this->fail("No menu item found.", 400);
}
$menuItemData = [];
if ($menuItem) {
$menu_tag = $this->menu_item_tags->where('menu_item_id', $menuItem['id'])->findAll();
$menu_option_group = $this->menu_item_options_groups->where('menu_item_id', $menuItem['id'])->findAll();
$menuItemData[] = [
'id' => $menuItem['id'],
'title' => $menuItem['title'],
'category' => getMenuCategory($menuItem['id']),
'short_description' => $menuItem['short_description'],
'long_description' => $menuItem['long_description'],
'price' => $menuItem['price'],
'order_index' => $menuItem['order_index'],
'availability_type' => $menuItem['availability_type'],
'availability' => getAvailability($menuItem['id'], $menuItem['availability_type']),
'status' => $menuItem['status'],
'image' => getMenuImage($menuItem['id']),
'created_at' => $menuItem['created_at'],
'menu_tag' => getMenuTag($menuItem['id']),
'menu_option_group' => getMenuOptionGroup($menuItem['id']),
'variation' => getVariationRelation($menuItem['id'])
];
}
return $this->respond(["status" => 200, "message" => "Successfully retrive data!", "data" => $menuItemData]);
}
public function showOption($id = null)
{
$group = $this->option_groups->find($id);
if (!$group) {
return $this->failNotFound("Option group not found.");
}
$group['options'] = $this->options
->where('option_group_id', $group['id'])
->where('deleted_at', null)
->findAll();
return $this->respond(['status' => 200, 'data' => $group]);
}
public function getAllMenus($outlet_id = null)
{
$db = \Config\Database::connect();
// Get all active categories first
$menu_categories = $db->table('menu_categories')
->select('id, title, image_url, status, compressed_image_url, order_index')
->where('status', 'active')
->where('deleted_at', null)
->orderBy('order_index', 'ASC')
->get()
->getResult();
// Get all tags for mapping
$all_tags = $db->table('tags')->select('id, title, icon_url')->get()->getResult();
$tagMap = [];
foreach ($all_tags as $tag) {
$tagMap[$tag->id] = [
'id' => $tag->id,
'title' => $tag->title,
'icon_url' => $tag->icon_url
];
}
$menu_items = [];
// Loop through each category to get corresponding items
foreach ($menu_categories as $category) {
// Get menu items for this category
$category_items = $db->table('menu_items')
->select('menu_items.id, menu_items.title, menu_items.short_description, menu_items.price, menu_items.availability_type, menu_items.order_index, menu_items.status, menu_items.membership_tier, menu_items.pwp')
->join('menu_item_categories', 'menu_item_categories.menu_item_id = menu_items.id')
->where('menu_item_categories.category_id', $category->id)
->where('menu_items.status', 'active')
->where('menu_items.deleted_at', null)
->orderBy('menu_items.order_index', 'ASC')
->get()
->getResult();
// Process each item in this category
foreach ($category_items as $item) {
// Get item images
$images = $db->table('menu_images')
->select('image_url, image_url_compressed')
->where('menu_item_id', $item->id)
->get()
->getResult();
// Get item tags
$menu_item_tags_links = $db->table('menu_item_tags')
->select('tag_id')
->where('menu_item_id', $item->id)
->get()
->getResult();
$tag_list = [];
foreach ($menu_item_tags_links as $tag_link) {
if (isset($tagMap[$tag_link->tag_id])) {
$tag_list[] = $tagMap[$tag_link->tag_id];
}
}
// Check if item is available in outlet
$is_available = $this->outlet_menus
->where('outlet_id', $outlet_id)
->where('menu_item_id', $item->id)
->first();
// Get category IDs for this item (should include current category)
$item_categories = $db->table('menu_item_categories')
->select('category_id')
->where('menu_item_id', $item->id)
->where('deleted_at', null)
->get()
->getResult();
$category_ids = [];
foreach ($item_categories as $cat_link) {
$category_ids[] = $cat_link->category_id;
}
$membership_tier = $item->membership_tier;
$menu_items[] = [
'id' => $item->id,
'title' => $item->title,
'short_description' => $item->short_description,
'price' => $item->price,
'availability_type' => $item->availability_type,
'order_index' => $item->order_index,
'status' => $item->status,
'images' => $images,
'category_ids' => $category_ids,
'tags' => $tag_list,
'is_available' => $is_available ? true : false,
'membership_tier' => $membership_tier,
'pwp' => $item->pwp,
];
}
}
return $this->response->setJSON([
'status' => 'success',
'response' => '200',
'Categories' => $menu_categories,
'Items' => $menu_items
]);
}
}
@@ -0,0 +1,748 @@
<?php
namespace App\Controllers\Frontend;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use App\Models\CartItemOptions;
use App\Models\CartItems;
use App\Models\Carts;
use App\Models\Customer;
use App\Models\CustomerWallet;
use App\Models\OrderItemOptions;
use App\Models\OrderItems;
use App\Models\OrderPayments;
use App\Models\Orders;
use App\Models\OrderTaxes;
use App\Models\Outlet;
use App\Models\MenuItemVariations;
use CodeIgniter\Database\Config;
use App\Libraries\Fiuu;
use App\Models\OrderDeliveries;
use App\Models\VoucherRedemptions;
use App\Models\PromoRedemptionRecord;
helper('outlet');
class OrderController extends ResourceController
{
private $carts;
private $cart_items;
private $cart_item_options;
private $orders;
private $order_items;
private $order_item_options;
private $order_payments;
private $order_taxes;
private $customer;
private $customer_wallet;
private $db;
private $cart_service;
private $calculate_service;
private $promo_service;
private $outlet;
private $fiuu;
private $voucher_service;
private $variations;
private $order_deliveries;
private $promo_redemptions_record;
private $voucher_redemptions;
public function __construct()
{
$this->carts = new Carts();
$this->cart_items = new CartItems();
$this->cart_item_options = new CartItemOptions();
$this->orders = new Orders();
$this->order_items = new OrderItems();
$this->order_item_options = new OrderItemOptions();
$this->customer = new Customer();
$this->order_payments = new OrderPayments();
$this->order_taxes = new OrderTaxes();
$this->customer_wallet = new CustomerWallet();
$this->db = Config::connect();
$this->cart_service = service('cartService');
$this->calculate_service = service('calculateService');
$this->promo_service = service('promoService');
$this->voucher_service = service('voucherService');
$this->outlet = new Outlet();
$this->fiuu = new Fiuu();
$this->variations = new MenuItemVariations();
$this->order_deliveries = new OrderDeliveries();
$this->promo_redemptions_record = new PromoRedemptionRecord();
$this->voucher_redemptions = new VoucherRedemptions();
}
public function createOrder()
{
$validation = $this->validate([
'customer_id' => 'required|numeric',
'outlet_id' => 'required|numeric',
'order_type' => 'required',
'customer_address_id' => 'permit_empty|numeric',
'payment_method' => 'required',
'selected_date' => 'permit_empty|string',
'selected_time' => 'permit_empty|string',
'latitude' => 'permit_empty|string',
'longitude' => 'permit_empty|string',
'notes' => 'permit_empty|string',
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$customer_id = $this->request->getVar('customer_id');
$outlet_id = $this->request->getVar('outlet_id');
$customer_address_id = $this->request->getVar('customer_address_id');
$order_type = strtolower(str_replace('-', '', $this->request->getVar('order_type')));
$payment_method = $this->request->getVar('payment_method');
$selected_date = $this->request->getVar('selected_date') ?? date('Y-m-d');
$selected_time = $this->request->getVar('selected_time') ?? date('H:i');
$real_selected_date = $this->request->getVar('selected_date');
$real_selected_time = $this->request->getVar('selected_time');
$latitude = $this->request->getVar('latitude');
$longitude = $this->request->getVar('longitude');
$notes = $this->request->getVar('notes');
$address = $this->request->getVar('address');
$cart = $this->carts->where('customer_id', $customer_id)
->where('outlet_id', $outlet_id)
->where('status', 'active')
->first();
if (!$cart) {
return $this->fail('Cart not found', 400);
}
$customer = $this->customer->find($customer_id);
if (!$customer) {
return $this->fail('Customer not found', 400);
}
$promo_or_voucher = null;
if ($cart['promo_code_id'] > 0) {
$check_promo = $this->promo_service->checkPromoAvailability($cart['promo_code_id'], $order_type, $customer_id);
if (isset($check_promo['status']) && $check_promo['status'] == 400) {
$this->calculate_service->resetVoucher($cart['id']);
return $this->respond($check_promo);
}
$promo_or_voucher = 'promo';
}
if ($cart['customer_voucher_list_id'] > 0) {
$check_voucher = $this->voucher_service->checkVoucherAvailability($cart['customer_voucher_list_id'], $order_type, $customer_id);
if (isset($check_voucher['status']) && $check_voucher['status'] == 400) {
$this->calculate_service->resetVoucher($cart['id']);
return $this->respond($check_voucher);
}
$promo_or_voucher = 'voucher';
}
$cart_total = $this->calculate_service->calculateCartTotals($cart['id'], $cart['outlet_id'], $real_selected_date, $real_selected_time, $latitude, $longitude, $order_type, $address, $promo_or_voucher);
// print_r($cart_total);
// exit;
if (isset($cart_total['status']) && $cart_total['status'] == 400) {
$response = [
'status' => 400,
'message' => $cart_total['message']
];
return $this->respond($response, 400);
}
$cart_total = $cart_total['data'];
if (count($cart_total['invalid_items']) > 0) {
return $this->fail('Menu got updated, try again', 400);
}
if ($payment_method == 'wallet') {
if ($customer['customer_wallet'] < $cart_total['order_summary']['grand_total']) {
return $this->fail('Insufficient Wallet Balance', 400);
}
}
if ($cart_total['order_summary']['grand_total'] < 0) {
return $this->fail('Invalid Grand Total', 400);
}
//check operation date and time
$check_operation_date_and_time = checkOperationDateAndTime($outlet_id, $selected_date, $selected_time);
if (!$check_operation_date_and_time) {
return $this->fail('Outlet is not operated on the selected date and time', 400);
}
$this->db->transStart();
try {
$orderData = [
'customer_id' => $customer_id,
'outlet_id' => $outlet_id,
'customer_address_id' => $customer_address_id,
'order_type' => $order_type,
'status' => 'pending',
'payment_status' => 'unpaid',
'packaging_charge' => $cart_total['order_summary']['packaging_charge'] ?? 0,
'payment_method' => $payment_method,
'subtotal_amount' => $cart_total['order_summary']['subtotal_amount'],
'discount_amount' => $cart_total['order_summary']['discount_amount'],
'tax_amount' => $cart_total['order_summary']['tax_amount'],
'delivery_fee' => $cart_total['order_summary']['delivery_fee'] ?? 0,
'rounding_amount' => $cart_total['order_summary']['rounding_amount'],
'grand_total' => $cart_total['order_summary']['grand_total'],
'promo_code_id' => $cart_total['order_summary']['promo_code_id'],
'promo_discount_amount' => $cart_total['order_summary']['promo_discount_amount'],
'customer_voucher_list_id' => $cart_total['order_summary']['customer_voucher_list_id'],
'voucher_discount_amount' => $cart_total['order_summary']['voucher_discount_amount'],
'placed_at' => '',
'selected_date' => $real_selected_date,
'selected_time' => $real_selected_time,
'expected_ready_time' => '',
'notes' => $notes,
'lalamove_quot_id' => $cart['lalamove_quot_id'] ?? null,
'grab_quot_id' => $cart['grab_quot_id'] ?? null
];
//insert order
$order_id = $this->orders->insert($orderData);
if ($promo_or_voucher != null) {
if ($promo_or_voucher == 'promo') {
$this->promo_redemptions_record->insert([
'order_id' => $order_id,
'promo_codes_id' => $orderData['promo_code_id'],
'customer_id' => $orderData['customer_id'],
]);
} else if ($promo_or_voucher == 'voucher') {
$this->voucher_redemptions->insert([
'order_id' => $order_id,
'customer_voucher_list_id' => $orderData['customer_voucher_list_id'],
'customer_id' => $orderData['customer_id'],
'order_type' => $orderData['order_type'],
]);
}
}
if ($order_id > 0) {
$today_order_count = $this->orders->where('created_at >=', date('Y-m-d 00:00:00'))->where('created_at <=', date('Y-m-d 23:59:59'))->countAllResults();
$order_so = date('ymd') . str_pad($today_order_count, 5, '0', STR_PAD_LEFT);
$this->orders->update($order_id, ['order_so' => $order_so]);
}
//insert order items
$cartItems = $this->cart_items->where('cart_id', $cart['id'])->findAll();
foreach ($cartItems as $cartItem) {
$orderItemData = [
'order_id' => $order_id,
'menu_item_id' => $cartItem['menu_item_id'],
'variation_id' => $cartItem['variation_id'],
'title' => $cartItem['title'],
'unit_price' => $cartItem['unit_price'],
'quantity' => $cartItem['quantity'],
'line_subtotal' => $cartItem['line_subtotal'],
'order_index' => $cartItem['order_index'],
];
$orderItemId = $this->order_items->insert($orderItemData);
$cartItemOptions = $this->cart_item_options->where('cart_item_id', $cartItem['id'])->findAll();
foreach ($cartItemOptions as $option) {
$orderItemOptionData = [
'order_item_id' => $orderItemId,
'option_id' => $option['option_id'],
'option_title' => $option['option_title'],
'price_adjustment' => $option['price_adjustment'],
];
$this->order_item_options->insert($orderItemOptionData);
}
}
//insert order taxes
foreach ($cart_total['tax_detail'] as $tax_order) {
$tax_data = [
'order_id' => $order_id,
'tax_type' => $tax_order['tax_type'],
'tax_rate' => $tax_order['tax_rate'],
'tax_amount' => $tax_order['tax_amount'],
];
$this->order_taxes->insert($tax_data);
}
$respond_data = [];
//insert order payments
if ($payment_method == 'wallet') {
$payment = [
'order_id' => $order_id,
'payment_method' => $payment_method,
'amount' => $cart_total['order_summary']['grand_total'],
'transaction_id' => 0,
'status' => 'pending',
'paid_at' => '',
];
// echo(123);exit;
$this->order_payments->insert($payment);
completeOrder($order_id);
} else {
//generate payment details & url
$payment = [
'order_id' => $order_id,
'payment_method' => $payment_method,
'amount' => $cart_total['order_summary']['grand_total'],
'transaction_id' => 0,
'status' => 'pending',
'paid_at' => '',
];
$this->order_payments->insert($payment);
$payment_details = [
'bill_name' => $customer['name'],
'bill_email' => $customer['email'],
'bill_mobile' => $customer['phone'],
'bill_desc' => 'US Pizza - Payment for ' . ucfirst($order_type) . ' - ' . $order_id,
];
$result = $this->fiuu->createPayment($order_so, $cart_total['order_summary']['grand_total'], $payment_details);
$respond_data['redirect_url'] = $result['redirect_url'];
}
$this->carts->update($cart['id'], ['status' => 'completed']);
$this->db->transComplete();
$order = $this->orders->find($order_id);
$order['items'] = $this->order_items->where('order_id', $order_id)->findAll();
foreach ($order['items'] as &$item) {
$item['options'] = $this->order_item_options->where('order_item_id', $item['id'])->findAll();
}
$respond_data['status'] = 200;
$respond_data['message'] = 'Order created successfully';
$respond_data['order'] = $order;
return $this->respond($respond_data);
} catch (\Exception $e) {
$this->db->transRollback();
print_r($e->getMessage());
return $this->fail('Cannot checkout order. Please try again.', 400);
}
}
public function createOrderAgain($order_id = null)
{
$order = $this->orders->select('orders.*, customer_addresses.address, customer_addresses.latitude, customer_addresses.longitude')
->join('customer_addresses', 'customer_addresses.id = orders.customer_address_id', 'left')
->find($order_id);
if (!$order) {
return $this->fail('Order not found', 400);
}
$outlet = $this->outlet->find($order['outlet_id']);
$outlet_title = $outlet['title'] ?? '';
//check outlet cart exist
$existing_cart = $this->carts
->where('customer_id', $order['customer_id'])
->where('outlet_id', $order['outlet_id'])
->where('status', 'active')
->first();
if ($existing_cart) {
//clear all cart items
$this->cart_items->where('cart_id', $existing_cart['id'])->delete();
}
//select order items
$order_items = $this->order_items->where('order_id', $order_id)->findAll();
// print_r($order_items);exit;
foreach ($order_items as $order_item) {
if ($order_item['unit_price'] > 0) {
$options = $this->order_item_options
->select('options.option_group_id, order_item_options.option_id')
->join('options', 'options.id = order_item_options.option_id')
->where('order_item_id', $order_item['id'])
->findAll();
$option_group = [];
if (!empty($options)) {
// Group options by option_group_id
$grouped_options = [];
foreach ($options as $option) {
$grouped_options[$option['option_group_id']][] = $option['option_id'];
}
// Convert to the expected format for cart service
foreach ($grouped_options as $group_id => $option_ids) {
$option_group[] = [
'group_id' => $group_id,
'option_ids' => $option_ids
];
}
}
// print_r($option_group);exit;
$addCart = $this->cart_service->addCartItem($order['customer_id'], $order['outlet_id'], $existing_cart, $order_item['menu_item_id'], $order_item['variation_id'], $option_group, $order_item['quantity'], false);
if (isset($addCart['status']) && $addCart['status'] == 400) {
return $this->fail($addCart['message'], 400);
}
}
}
$data = [
'order_id' => $order['id'],
'customer_id' => $order['customer_id'],
'outlet_id' => $order['outlet_id'],
'outlet_title' => $outlet_title,
'customer_address_id' => $order['customer_address_id'],
'order_type' => $order['order_type'],
'address' => $order['address'],
'latitude' => $order['latitude'],
'longitude' => $order['longitude']
];
return $this->respond(['status' => 200, 'message' => 'Order created successfully', 'data' => $data]);
}
public function createOrderVip()
{
$customer_id = $this->request->getVar('customer_id');
$outlet_id = HQ_OUTLET_ID;
$outlet = $this->outlet->find($outlet_id);
$order_type = 'dinein';
$outlet_title = $outlet['title'] ?? '';
//check outlet cart exist
$existing_cart = $this->carts
->where('customer_id', $customer_id)
->where('outlet_id', $outlet_id)
->where('status', 'active')
->first();
if ($existing_cart) {
//clear all cart items
$this->cart_items->where('cart_id', $existing_cart['id'])->delete();
}
//select VIP Cart Item
$addCart = $this->cart_service->addCartItem($customer_id, $outlet_id, $existing_cart, VIP_MENU_ITEM_ID, 0, [], 1, false);
if (isset($addCart['status']) && $addCart['status'] == 400) {
return $this->fail($addCart['message'], 400);
}
$data = [
'customer_id' => $customer_id,
'outlet_id' => $outlet_id,
'outlet_title' => $outlet_title,
'order_type' => $order_type,
];
return $this->respond(['status' => 200, 'message' => 'Order created successfully', 'data' => $data]);
}
public function showOrder($order_id = null)
{
// echo(123);exit;
$order = $this->orders->find($order_id);
if (!$order) {
return $this->fail('Order not found', 400);
}
//calculate grad_total before rounding
$grand_total_before_rounding = $order['grand_total'] - $order['rounding_amount'];
$order['grand_total_before_rounding'] = number_format($grand_total_before_rounding, 2);
$order['items'] = $this->order_items->where('order_id', $order_id)->findAll();
foreach ($order['items'] as &$item) {
$item['variation'] = $this->variations->find($item['variation_id']);
$item['options'] = $this->order_item_options->where('order_item_id', $item['id'])->findAll();
}
$order['taxes'] = $this->order_taxes->where('order_id', $order_id)->findAll();
$order['payments'] = $this->order_payments
->where('order_id', $order_id)
->orderBy('created_at', 'DESC')
->findAll();
$order['deliveries'] = $this->order_deliveries
->where('order_id', $order_id)
->orderBy('created_at', 'DESC')
->findAll();
$order['packaging_charge'] = $order['packaging_charge'] ?? 0;
$order['points'] = floor($order['grand_total']);
// print_r($order);exit;
return $this->respond([
'status' => 200,
'message' => 'Order retrieved successfully',
'data' => $order
]);
}
public function orderList($customer_id)
{
$start_date = $this->request->getVar('start_date');
$end_date = $this->request->getVar('end_date');
$status = $this->request->getVar('status');
$order_type = $this->request->getVar('order_type');
$orderQuery = $this->orders
->where('customer_id', $customer_id)
->orderBy('created_at', 'DESC');
if (!empty($start_date)) {
$orderQuery->where('created_at >=', $start_date . ' 00:00:00');
}
if (!empty($end_date)) {
$orderQuery->where('created_at <=', $end_date . ' 23:59:59');
}
if (!empty($status)) {
$orderQuery->where('status', $status);
}
if (!empty($order_type)) {
$orderQuery->where('order_type', $order_type);
}
$orders = $orderQuery->findAll();
if (empty($orders)) {
return $this->respond([
'status' => 200,
'message' => 'No orders found for this customer',
'data' => []
]);
}
foreach ($orders as &$order) {
$order_id = $order['id'];
$order['items'] = $this->order_items->where('order_id', $order_id)->findAll();
foreach ($order['items'] as &$item) {
$item['options'] = $this->order_item_options
->where('order_item_id', $item['id'])
->findAll();
}
$order['taxes'] = $this->order_taxes
->where('order_id', $order_id)
->findAll();
$order['payments'] = $this->order_payments
->where('order_id', $order_id)
->orderBy('created_at', 'DESC')
->findAll();
$order['packaging_charge'] = $order['packaging_charge'] ?? 0;
}
return $this->respond([
'status' => 200,
'message' => 'Orders retrieved successfully',
'data' => $orders
]);
}
// public function applyPromoCode(){
// $validation = $this->validate([
// 'promo_code' => 'required',
// 'cart_id' => 'required|numeric',
// 'outlet_id' => 'required|numeric',
// ]);
// if (!$validation) {
// return $this->failValidationErrors($this->validator->getErrors());
// }
// $promo_code = $this->request->getVar('promo_code');
// $cart_id = $this->request->getVar('cart_id');
// $outlet_id = $this->request->getVar('outlet_id');
// $free_item = $this->request->getVar('free_item') ?? [];
// if(empty($promo_code)){
// return $this->respond(['status' => 400, 'result' => 'Promo code is empty.']);
// }
// $promo_code_id = $this->promo_service->checkPromoCode($promo_code);
// if(isset($promo_code_id['status']) && $promo_code_id['status'] == 400){
// //error message respond
// return $this->respond($promo_code_id);
// }
// //update promo id
// $this->carts->update($cart_id, ['promo_code_id' => $promo_code_id]);
// $applyPromoCode = $this->calculate_service->calculateCartTotals($cart_id, $outlet_id, null, null, null, null, null, null, $free_item);
// return $this->respond($applyPromoCode);
// }
//get all active outlets
// public function outletList()
// {
// $outlets = $this->outlet->getActiveOperatingHoursWithDaysList();
// if(empty($outlets)){
// return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
// }
// return $this->respond(['status' => 200, 'result' => $outlets]);
// }
public function index()
{
$outlets = $this->outlet->getOperatingHoursWithDaysList();
if (empty($outlets)) {
return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
}
return $this->respond(['status' => 200, 'result' => $outlets]);
}
public function nearestOutletList($mode = null, $latitude = null, $longitude = null)
{
$outlets = $this->outlet->getActiveOperatingHoursWithDaysListAndDistance($mode, $latitude, $longitude);
if (empty($outlets)) {
return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
}
return $this->respond(['status' => 200, 'result' => $outlets]);
}
public function showOutlet($outlet_id = null)
{
$result = $this->outlet->getOperatingHoursWithDays($outlet_id);
if (empty($result)) {
return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
}
return $this->respond(['status' => 200, 'result' => $result]);
}
public function checkPayment($order_id = null)
{
$order = $this->orders->find($order_id);
if (!$order) {
return $this->fail('Order not found', 400);
}
$payment_status = $order['payment_status'];
if ($payment_status == 'paid') {
return $this->respond(['status' => 200, 'result' => 'Success', 'order_id' => $order_id]);
} else if ($payment_status == 'pending') {
return $this->respond(['status' => 200, 'result' => 'Pending', 'order_id' => $order_id]);
} else {
return $this->respond(['status' => 400, 'result' => 'Failed', 'order_id' => $order_id]);
}
}
/**
* Get driver location coordinates for real-time tracking
* Called every 5 seconds from mobile app
*/
public function getDriverLocation()
{
// Get order ID from request
$order_id = $this->request->getPost('order_id') ?? $this->request->getGet('order_id');
if (!$order_id) {
return $this->respond([
'status' => 'error',
'message' => 'Order ID is required',
'data' => null
], 400);
}
// Get order details
$orders = new Orders();
$order = $orders->select('orders.*, order_deliveries.provider_name, order_deliveries.provider_order_id, order_deliveries.status')
->join('order_deliveries', 'order_deliveries.order_id = orders.id', 'left')
->where('orders.id', $order_id)
->where('orders.deleted_at', null)
->first();
if (!$order) {
return $this->respond([
'status' => 'error',
'message' => 'Order not found',
'data' => null
], 404);
}
// Check if order has delivery
if (!$order['provider_name'] || !$order['provider_order_id']) {
return $this->respond([
'status' => 'error',
'message' => 'Order has no active delivery',
'data' => null
], 400);
}
$driver_location = null;
$error_message = null;
try {
// Check delivery provider and call respective API
if ($order['provider_name'] === 'Lalamove') {
$lalamove = new \App\Libraries\Lalamove();
$driver_location = $lalamove->getDriverLocation($order['provider_order_id']);
if (!$driver_location || isset($driver_location['error'])) {
$error_message = 'Unable to fetch Lalamove driver location';
}
} elseif ($order['provider_name'] === 'Grab') {
$grab = new \App\Libraries\Grab();
$driver_location = $grab->getDriverLocation($order['provider_order_id']);
if (!$driver_location || isset($driver_location['error'])) {
$error_message = 'Unable to fetch Grab driver location';
}
} else {
return $this->respond([
'status' => 'error',
'message' => 'Unsupported delivery provider: ' . $order['provider_name'],
'data' => null
], 400);
}
} catch (Exception $e) {
log_message('error', 'Driver location API error: ' . $e->getMessage());
$error_message = 'Failed to fetch driver location';
}
// If there's an error, return error response
if ($error_message) {
return $this->respond([
'status' => 'error',
'message' => $error_message,
'data' => null
], 500);
}
// Return driver location data
return $this->respond([
'status' => 'success',
'message' => 'Driver location retrieved successfully',
'data' => [
'order_id' => $order_id,
'provider' => $order['provider_name'],
'delivery_status' => $order['status'],
'driver_location' => $driver_location,
'timestamp' => date('Y-m-d H:i:s'),
'last_updated' => time()
]
], 200);
}
}
@@ -0,0 +1,97 @@
<?php
namespace App\Controllers\Frontend;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\API\ResponseTrait;
use App\Models\Orders;
class PaymentController extends BaseController
{
use ResponseTrait;
private $fiuu;
private $order;
public function __construct()
{
$this->fiuu = new \App\Libraries\Fiuu();
$this->order = new Orders();
}
// public function createPayment()
// {
// $data = $this->request->getJSON(true); // true = associative array
// $amount = $data['amount'] ?? '0.00';
// $orderId = $data['order_id'] ?? 'UNKNOWN';
// // log_message('debug', " order_id: $orderId, amount: $amount");
// $result = $this->fiuu->createPayment($orderId, $amount);
// return $this->response->setJSON($result);
// }
public function createPayment()
{
$data = $this->request->getJSON(true);
$orderId = $data['order_id'] ?? 'UNKNOWN';
$amount = $data['amount'] ?? '0.00';
$customer = [
'name' => $data['bill_name'] ?? 'John Doe',
'email' => $data['bill_email'] ?? 'johndoe@example.com',
'mobile' => $data['bill_mobile'] ?? '601133094116',
'desc' => $data['bill_desc'] ?? 'Test payment',
'address' => $data['bill_address'] ?? '123 Jalan Teknologi',
'postcode' => $data['bill_postcode'] ?? '47000',
'city' => $data['bill_city'] ?? 'Petaling Jaya',
'state' => $data['bill_state'] ?? 'Selangor',
'country' => $data['bill_country'] ?? 'MY'
];
// Call the updated Fiuu library method
$result = $this->fiuu->createPayment($orderId, $amount, $customer);
return $this->response->setJSON($result);
}
public function fiuuPaymentReturn()
{
$data = $this->request->getPost();
$this->fiuu->paymentNotification($data);
}
public function fiuuPaymentNotification()
{
$data = $this->request->getPost();
$this->fiuu->paymentNotification($data);
}
public function payAgain($order_id){
$order = $this->order->select('orders.*, customers.name, customers.email, customers.phone')
->join('customers', 'customers.id = orders.customer_id')
->where('orders.id', $order_id)
->where('orders.payment_status', 'unpaid')
->first();
if(!$order){
return $this->fail('Order not found', 400);
}
$payment_details = [
'bill_name' => $order['name'],
'bill_email' => $order['email'],
'bill_mobile' => $order['phone'],
'bill_desc' => 'US Pizza - Payment for ' . ucfirst($order['order_type']) . ' - ' . $order['order_so'],
];
$respond_data = [];
$result = $this->fiuu->createPayment($order['order_so'], $order['grand_total'], $payment_details);
$respond_data['redirect_url'] = $result['redirect_url'];
$respond_data['status'] = 200;
$respond_data['message'] = 'Payment link generated successfully';
return $this->respond($respond_data);
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Controllers\Frontend;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class SlideshowController extends BaseController
{
public function index()
{
$slideshowModel = new \App\Models\SlideshowModel();
$allowedOrderFields = [
'order', 'created_at', 'updated_at', 'title', 'status'
];
$orderBy = $this->request->getGet('order_by') ?? 'order';
$sort = strtolower($this->request->getGet('sort')) === 'desc' ? 'DESC' : 'ASC';
$page = (int) ($this->request->getGet('page') ?? 1);
$limit = (int) ($this->request->getGet('limit') ?? 20);
if (!in_array($orderBy, $allowedOrderFields)) {
$orderBy = 'order';
}
$builder = $slideshowModel->orderBy($orderBy, $sort)->where('deleted_at', null);
if ($limit > 0) {
$offset = ($page - 1) * $limit;
$slides = $builder->findAll($limit, $offset);
$total = $slideshowModel->where('deleted_at', null)->countAllResults();
} else {
$slides = $builder->findAll();
$total = count($slides);
}
return $this->response->setJSON([
'status' => 200,
'result' => $slides,
'pagination' => [
'page' => $page,
'limit' => $limit,
'total' => $total
]
]);
}
}
@@ -0,0 +1,345 @@
<?php
namespace App\Controllers\Frontend;
use App\Controllers\BaseController;
use App\Models\TopupModel;
use App\Libraries\Fiuu;
use CodeIgniter\API\ResponseTrait;
use App\Models\Customer;
use App\Models\CustomerWallet;
class TopupController extends BaseController
{
use ResponseTrait;
private $topups;
private $fiuu;
private $customer;
private $wallets;
private $db;
public function __construct()
{
$this->topups = new TopupModel();
$this->fiuu = new Fiuu();
$this->customer = new Customer();
$this->wallets = new CustomerWallet();
$this->db = db_connect();
}
public function index()
{
$data = $this->topups
->orderBy('created_at', 'DESC')
->findAll();
return $this->respond([
'status' => 200,
'data' => $data,
]);
}
private function createPendingWalletRow(array $topupRow, array $customer): void
{
$current = (float)($customer['customer_wallet'] ?? 0);
$incoming = (float)($topupRow['credit'] ?? 0);
if ($incoming <= 0) {
$incoming = (float)($topupRow['other_amount'] ?? 0);
}
$walletData = [
'customer_id' => $topupRow['customer_id'],
'related_type' => 'topup',
'related_id' => $topupRow['id'],
'action' => 'in',
'current' => $current,
'in' => $incoming,
'out' => 0,
'balance' => $current,
'remark' => 'Topup '.$topupRow['topup_number'].' (pending)',
'status' => 'Pending',
'created_at' => date('Y-m-d H:i:s'),
];
try {
$this->wallets->insert($walletData, true);
} catch (\Throwable $e) {
}
}
public function createTopupPayment()
{
$data = $this->request->getJSON(true);
$rules = [
'customer_id' => 'required|integer',
'payment_method' => 'required|string|max_length[50]',
'topup_setting_id' => 'permit_empty|integer',
'amount' => 'permit_empty|decimal',
'credit' => 'permit_empty|decimal',
'other_amount' => 'permit_empty|decimal'
];
if (!$this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$topupSettingId = !empty($data['topup_setting_id']) ? (int)$data['topup_setting_id'] : null;
if ($topupSettingId) {
// MODE 1: package top-up
$pkg = model('App\Models\TopupSettingModel')
->where('id', $topupSettingId)
->where('deleted_at', null)
->first();
if (!$pkg || ($pkg['status'] ?? '') !== 'active') {
return $this->failValidationErrors(['topup_setting_id' => 'Selected package is invalid or inactive']);
}
$amount = (float)$pkg['topup_amount'];
$credit = (float)$pkg['credit_amount'];
if ($amount <= 0 || $credit <= 0) {
return $this->failValidationErrors(['topup_setting' => 'Package amounts must be > 0']);
}
$otherAmount = null;
} else {
$otherAmount = isset($data['other_amount']) && $data['other_amount'] !== '' ? (float)$data['other_amount'] : 0.0;
if ($otherAmount <= 0) {
return $this->failValidationErrors(['other_amount' => 'Provide a positive amount for custom top-up']);
}
$amount = 0.0;
$credit = 0.0;
}
$topupNumber = 'T' . strtoupper(bin2hex(random_bytes(6)));
$insertData = [
'topup_setting_id' => $topupSettingId,
'customer_id' => (int)$data['customer_id'],
'topup_number' => $topupNumber,
'amount' => $amount, // package cash (0 for custom)
'credit' => $credit, // package credit (0 for custom)
'payment_method' => $data['payment_method'],
'other_amount' => $otherAmount, // used for custom
'status' => 'Pending',
];
$id = $this->topups->insert($insertData, true);
if (!$id) return $this->fail('Topup failed', 400);
$topup = $this->topups->find($id);
$customer = $this->customer->find((int)$data['customer_id']) ?? [];
// Write PENDING wallet ledger (no balance change yet)
$this->createPendingWalletRow($topup, $customer);
// Payment link uses the payable amount:
// - package mode → $amount
// - custom mode → $otherAmount
$payable = $topupSettingId ? $amount : $otherAmount;
$payment_details = [
'bill_name' => $customer['name'] ?? '',
'bill_email' => $customer['email'] ?? '',
'bill_mobile' => $customer['phone'] ?? '',
'bill_desc' => 'US Pizza - Wallet Topup - ' . $topupNumber,
];
$result = $this->fiuu->createTopup($topupNumber, $payable, $payment_details);
return $this->respond([
'status' => 201,
'message' => 'Topup created successfully',
'data' => $this->topups->find($id),
'redirect_url' => $result['redirect_url'] ?? null
]);
}
public function fiuuTopupNotification()
{
$payload = $this->request->getPost();
// $payload = $this->request->getJSON(true);
// print_r($payload);exit;
$result = $this->fiuu->topupNotification($payload);
log_message('error', 'Fiuu Payload: '.json_encode($payload));
log_message('error', 'Fiuu Result: '.json_encode($result));
$topupNumber = $payload['orderid'] ?? null;
if (!$topupNumber) {
return $this->respond(['status' => 400, 'message' => 'Missing orderid'], 400);
}
$topup = $this->topups->where('topup_number', $topupNumber)->first();
if (!$topup) {
return $this->respond(['status' => 404, 'message' => 'Topup not found'], 404);
}
if (in_array($topup['status'], ['completed','failed'], true)) {
return $this->respond(['status' => 200, 'message' => 'Already processed', 'result' => $result]);
}
$payStat = strtolower((string)($payload['status'] ?? ''));
$resStat = is_array($result) ? strtolower((string)($result['status'] ?? '')) : strtolower((string)$result);
$isSuccess = in_array($payStat, ['00','success','approved'], true)
|| (is_string($resStat) && strpos($resStat, 'success') !== false);
$this->db->transStart();
if ($isSuccess) {
$table = $this->customer->builder()->getTable();
$customer = $this->db->query(
'SELECT * FROM `'.$table.'` WHERE `id` = ? FOR UPDATE',
[$topup['customer_id']]
)->getRowArray();
if (!$customer) {
$this->db->transRollback();
return $this->respond(['status' => 404, 'message' => 'Customer not found'], 404);
}
$current = (float)($customer['customer_wallet'] ?? 0);
$delta = $topup['amount'] + $topup['credit'];
// print_r($delta);exit;
if ($delta <= 0) $delta = (float)$topup['other_amount'];
if ($delta <= 0) {
$this->topups->update($topup['id'], ['status' => 'failed']);
$this->db->transComplete();
return $this->respond(['status' => 400, 'message' => 'Invalid topup amount'], 400);
}
$newBal = $current + $delta;
$walletRow = $this->wallets
->where('related_type', 'topup')
->where('related_id', $topup['id'])
->orderBy('id', 'desc')
->first();
if ($walletRow) {
$this->wallets->update($walletRow['id'], [
'status' => 'completed',
'current' => $current,
'balance' => $newBal,
'remark' => 'Topup '.$topupNumber.' (completed)',
'in' => $delta,
]);
} else {
$this->wallets->insert([
'customer_id' => $topup['customer_id'],
'related_type' => 'topup',
'related_id' => $topup['id'],
'action' => 'in',
'current' => $current,
'in' => $delta,
'out' => 0,
'balance' => $newBal,
'remark' => 'Topup '.$topupNumber.' (completed)',
'status' => 'completed',
'created_at' => date('Y-m-d H:i:s'),
], true);
}
$this->customer->update($customer['id'], ['customer_wallet' => $newBal]);
$this->topups->update($topup['id'], ['status' => 'Success']);
} else {
$this->topups->update($topup['id'], ['status' => 'Failed']);
$this->wallets
->where('related_type', 'topup')
->where('related_id', $topup['id'])
->set([
'status' => 'failed',
'remark' => 'Topup '.$topupNumber.' (failed)'
])->update();
}
$this->db->transComplete();
if ($this->db->transStatus() === false) {
return $this->respond(['status' => 500, 'message' => 'Transaction error'], 500);
}
return $this->respond(['status' => 200, 'message' => 'Notification processed', 'result' => $result]);
}
public function fiuuTopupReturn()
{
$data = $this->request->getPost();
$this->fiuu->topupNotification($data);
}
public function checkTopupPayment($topup_id = null)
{
// echo(123123);exit;
$topup = $this->topups->find($topup_id);
if (!$topup) {
return $this->fail('Topup not found', 400);
}
// print_r($topup);exit;
$status = strtolower($topup['status'] ?? '');
// print_r($status);exit;
if ($status === 'success') {
return $this->respond(['status' => 200, 'result' => 'Success', 'topup_id' => $topup_id]);
} elseif ($status === 'pending') {
return $this->respond(['status' => 200, 'result' => 'Pending', 'topup_id' => $topup_id]);
}
return $this->respond(['status' => 400, 'result' => 'Failed', 'topup_id' => $topup_id]);
}
public function show($id = null)
{
$id = (int) $id;
$row = $this->topups
->select('topup.*, topup_setting.id AS setting_id, topup_setting.topup_amount, topup_setting.credit_amount, topup_setting.status AS setting_status')
->join('topup_setting', 'topup_setting.id = topup.topup_setting_id', 'left')
->where('topup.id', $id)
->first();
if (!$row) {
return $this->failNotFound('Topup record not found');
}
$data = [
'id' => $row['id'],
'topup_setting_id' => $row['topup_setting_id'],
'customer_id' => $row['customer_id'],
'topup_number' => $row['topup_number'],
'amount' => $row['amount'],
'credit' => $row['credit'],
'payment_method' => $row['payment_method'],
'other_amount' => $row['other_amount'],
'status' => $row['status'],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
'topup_setting' => [
'id' => $row['setting_id'],
'topup_amount' => $row['topup_amount'],
'credit_amount' => $row['credit_amount'],
'status' => $row['setting_status']
]
];
return $this->respond([
'status' => 200,
'data' => $data
]);
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Controllers\Frontend;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\API\ResponseTrait;
use App\Models\TopupSettingModel;
class TopupSettingController extends BaseController
{
use ResponseTrait;
private $settings;
public function __construct()
{
$this->settings = new TopupSettingModel();
}
public function index()
{
$data = $this->settings
->orderBy('topup_amount', 'ASC')
->findAll();
return $this->respond([
'status' => 200,
'data' => $data,
]);
}
}
@@ -0,0 +1,508 @@
<?php
namespace App\Controllers\Frontend;
use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Customer;
use App\Models\CustomerVoucherList;
use App\Models\PromoCode;
use App\Models\PromoSetting;
use App\Models\Carts;
use App\Models\VoucherPoints;
use App\Models\MenuItems;
use App\Models\MenuItemCategories;
use App\Models\CustomerPoint;
class VoucherController extends BaseController
{
use ResponseTrait;
private $customers;
private $customer_voucher_list;
private $customer_points;
private $promo_codes;
private $promo_settings;
private $carts;
private $calculate_service;
private $promo_service;
private $voucher_service;
private $menuItem;
private $menuItemCategories;
private $voucher_points;
public function __construct()
{
$this->customers = new Customer();
$this->voucher_points = new VoucherPoints();
$this->customer_voucher_list = new CustomerVoucherList();
$this->promo_codes = new PromoCode();
$this->promo_settings = new PromoSetting();
$this->carts = new Carts();
$this->calculate_service = service('calculateService');
$this->promo_service = service('promoService');
$this->voucher_service = service('voucherService');
$this->menuItem = new MenuItems();
$this->menuItemCategories = new MenuItemCategories();
}
public function claim()
{
// echo(123);exit;
$body = $this->request->getJSON(true) ?? $this->request->getPost();
$customerId = (int) ($body['customer_id'] ?? 0);
$voucherId = (int) ($body['voucher_id'] ?? 0);
if ($customerId <= 0 || $voucherId <= 0) {
return $this->respond(['status' => 400, 'message' => 'Missing customer_id or voucher_id'], 400);
}
$voucherModel = $this->voucher_points;
$custPtsModel = new CustomerPoint();
$custVoucherMod = new CustomerVoucherList();
$voucher = $voucherModel
->where('id', $voucherId)
->where('voucher_status', 'active')
->first();
if (!$voucher) {
return $this->respond(['status' => 404, 'message' => 'Voucher not found or inactive'], 404);
}
if (!empty($voucher['voucher_total_count']) && !empty($voucher['voucher_redeem_count'])) {
if ((int)$voucher['voucher_redeem_count'] >= (int)$voucher['voucher_total_count']) {
return $this->respond(['status' => 400, 'message' => 'Voucher is out of stock'], 400);
}
}
if (!empty($voucher['voucher_count_customer'])) {
$taken = $custVoucherMod->where([
'customer_id' => $customerId,
'promo_setting_id' => $voucher['promo_setting_id'] ?? null,
])->where('voucher_status !=', 'trash')->countAllResults();
if ($taken >= (int)$voucher['voucher_count_customer']) {
return $this->respond(['status' => 400, 'message' => 'You have reached the redeem limit for this voucher'], 400);
}
}
$today = date('Y-m-d');
if (!empty($voucher['voucher_expired_date']) && $today > $voucher['voucher_expired_date']) {
return $this->respond(['status' => 400, 'message' => 'Voucher already expired'], 400);
}
$lastLedger = $custPtsModel->where('customer_id', $customerId)
->orderBy('id', 'DESC')->first();
$currentBalance = $lastLedger ? (float)$lastLedger['balance'] : 0.0;
$costPoints = (float) ($voucher['voucher_point_redeem'] ?? 0);
if ($costPoints <= 0) {
return $this->respond(['status' => 400, 'message' => 'Voucher point cost is invalid'], 400);
}
if ($currentBalance < $costPoints) {
return $this->respond(['status' => 400, 'message' => 'Insufficient points'], 400);
}
$custVoucherExpiry = null;
$type = strtolower(trim($voucher['voucher_expiry_type'] ?? ''));
$value = trim($voucher['voucher_expiry_value'] ?? '');
if ($type === 'date' && !empty($voucher['voucher_expired_date'])) {
$custVoucherExpiry = $voucher['voucher_expired_date'];
} elseif ($type === 'fixed' || $type === 'days') {
$days = (int)$value;
$custVoucherExpiry = date('Y-m-d', strtotime("+{$days} days"));
} else {
$custVoucherExpiry = !empty($voucher['voucher_expired_date']) ? $voucher['voucher_expired_date'] : null;
}
$already = $custVoucherMod->where([
'customer_id' => $customerId,
'promo_setting_id' => $voucher['promo_setting_id'] ?? null,
'voucher_status' => 'active',
])->first();
if ($already) {
return $this->respond(['status' => 200, 'message' => 'Voucher already redeemed for this customer', 'data' => $already]);
}
$db = \Config\Database::connect();
$db->transStart();
$voucherCode = strtoupper('V' . $voucherId . '-' . bin2hex(random_bytes(3)));
$custVoucherId = $custVoucherMod->insert([
'promo_setting_id' => $voucher['promo_setting_id'] ?? null,
'customer_id' => $customerId,
'voucher_order_id' => 0,
'voucher_topup_id' => 0,
'voucher_code' => $voucherCode,
'voucher_expiry_date'=> $custVoucherExpiry,
'voucher_status' => 'active',
], true);
$newBalance = $currentBalance - $costPoints;
$ledgerId = $custPtsModel->insert([
'customer_id' => $customerId,
'related_id' => $voucherId,
'related_type'=> 'voucher',
'action' => 'redeem_voucher',
'current' => $currentBalance,
'in' => 0,
'out' => $costPoints,
'balance' => $newBalance,
'remark' => sprintf('Redeemed voucher "%s" (ID %d, code %s)', $voucher['voucher_name'] ?? '', $voucherId, $voucherCode),
], true);
$this->customers->update($customerId, [
'customer_point' => $newBalance
]);
$voucherModel->where('id', $voucherId)->set('voucher_redeem_count', 'voucher_redeem_count + 1', false)->update();
$db->transComplete();
if ($db->transStatus() === false) {
return $this->respond(['status' => 500, 'message' => 'Failed to redeem voucher'], 500);
}
return $this->respond([
'status' => 200,
'message' => 'Voucher redeemed successfully',
'data' => [
'customer_voucher_id' => $custVoucherId,
'ledger_id' => $ledgerId,
'voucher_code' => $voucherCode,
'new_balance' => $newBalance,
'voucher_expiry_date' => $custVoucherExpiry,
],
]);
}
public function index()
{
// echo(123123);exit;
log_message('info', 'Voucher index accessed');
$voucherName = $this->request->getGet('voucher_name');
$dateFrom = $this->request->getGet('date_from');
$dateTo = $this->request->getGet('date_to');
$builder = $this->voucher_points->builder();
$builder->where('voucher_status !=', 'trash');
if ($voucherName) {
$builder->like('voucher_name', $voucherName);
}
if ($dateFrom && $dateTo) {
$builder->where('voucher_expired_date >=', $dateFrom);
$builder->where('voucher_expired_date <=', $dateTo);
}
// ✅ Print the generated SQL
// echo $builder->getCompiledSelect();
// exit;
// All transactions
$voucherSettings = $builder->get()->getResult();
if (empty($voucherSettings)) {
return $this->respond(["status" => 400, "message" => "No Voucher Found", "data" => []]);
}
return $this->respond(["status" => 200, "message" => "Successfully retrive data!", "data" => $voucherSettings]);
}
public function show($id = null)
{
$voucherSettings = $this->voucher_points->find($id);
if (empty($voucherSettings)) {
return $this->fail("No voucher settings found.", 400);
}
$voucherSettingData = [];
if ($voucherSettings) {
$voucherSettingData[] = [
'id' => $voucherSettings['id'],
'voucher_name' => $voucherSettings['voucher_name'],
'voucher_total_count' => $voucherSettings['voucher_total_count'],
'voucher_redeem_count' => $voucherSettings['voucher_redeem_count'],
'voucher_count_customer' => $voucherSettings['voucher_count_customer'],
'voucher_expiry_type' => $voucherSettings['voucher_expiry_type'],
'voucher_expiry_value' => $voucherSettings['voucher_expiry_value'],
'voucher_expired_date' => $voucherSettings['voucher_expired_date'],
'voucher_point_redeem' => $voucherSettings['voucher_point_redeem'],
'promo_setting_id'=> $voucherSettings['promo_setting_id'],
'voucher_details'=> $voucherSettings['voucher_details'],
'voucher_tnc'=> $voucherSettings['voucher_tnc'],
'voucher_status'=> $voucherSettings['voucher_status'],
'voucher_image_url'=> getImagePath('vouchers', $voucherSettings['voucher_image']),
];
}
return $this->respond(["status" => 200, "message" => "Successfully retrive data!", "data" => $voucherSettingData]);
}
public function voucherList($customer_id)
{
if(empty($customer_id)) {
return $this->respond(['status' => 400, 'result' => 'Customer ID is empty.']);
}
$customer = $this->customers->find($customer_id);
if(empty($customer)) {
return $this->respond(['status' => 400, 'result' => 'Customer data not found.']);
}
$customer_voucher_list = $this->customer_voucher_list
->select('customer_voucher_list.*, promo_settings.description')
->join('promo_settings', 'promo_settings.id = customer_voucher_list.promo_setting_id')
->where('customer_voucher_list.customer_id', $customer_id)
->findAll();
return $this->respond(['status' => 200, 'message' =>'Customer voucher list retrieved sucessfully!', 'data' => $customer_voucher_list]);
}
public function redeemVoucher($customer_id)
{
if(empty($customer_id)) {
return $this->respond(['status' => 400, 'result' => 'Customer ID is empty.']);
}
$customer = $this->customers->find($customer_id);
if(empty($customer)) {
return $this->respond(['status' => 400, 'result' => 'Customer data not found.']);
}
$validation = $this->validate([
'order_type' => 'required',
'promo_code' => 'permit_empty',
'voucher_id' => 'permit_empty',
'cart_id' => 'required',
'outlet_id' => 'required',
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$promo_code = $this->request->getVar('promo_code');
$voucher_id = $this->request->getVar('voucher_id');
$cart_id = $this->request->getVar('cart_id');
$outlet_id = $this->request->getVar('outlet_id');
$order_type = $this->request->getVar('order_type');
if(empty($promo_code) && empty($voucher_id)) {
return $this->respond(['status' => 400, 'result' => 'Voucher code or voucher id is empty.']);
}
$getCart = $this->carts->where('customer_id', $customer_id)->where('outlet_id', $outlet_id)->where('status', 'active')->find($cart_id);
if(empty($getCart)) {
return $this->respond(['status' => 400, 'result' => 'Unable to find your cart.']);
}
if($getCart['promo_code_id'] > 0 || $getCart['customer_voucher_list_id'] > 0) {
$getCart['promo_code_id'] = 0;
$getCart['customer_voucher_list_id'] = 0;
$this->carts->update($cart_id, $getCart);
}
$free_items = [];
if(!empty($promo_code)) {
// promo code
$promo = $this->promo_codes->select('promo_codes.*, promo_settings.promo_setting')
->where('promo_codes.code', $promo_code)
->join('promo_settings', 'promo_settings.id = promo_codes.promo_setting_id')
->orderBy('promo_codes.id', 'DESC')->first();
if(empty($promo)) {
return $this->respond(['status' => 400, 'result' => 'Code not found.']);
}
$promoSettingData = json_decode($promo['promo_setting'], true);
$promo_setting = $promoSettingData['Promo'];
// print_r($promo);exit;
//check promo availability
$check_promo = $this->promo_service->checkPromoAvailability($promo['id'], $order_type, $customer_id);
//promo unavailable
if(isset($check_promo['status']) && $check_promo['status'] == 400) {
return $this->respond($check_promo);
}
if($promo_setting['promo_type'] == 'free_item'){
$free_items = [];
$isIncluded = true;
if($promo_setting['filter_type'] == 'item'){
foreach($promo_setting['free_item'] as $free_item_id){
$menu_item = $this->menuItem
->select('menu_items.id, menu_items.title, menu_images.image_url, menu_images.image_url_compressed')
->join('menu_images', 'menu_images.menu_item_id = menu_items.id', 'left')
->where('menu_items.status', 'active')
->find($free_item_id);
if($menu_item){
$free_items[] = [
'id' => $menu_item['id'],
'title' => $menu_item['title'],
'image_url' => getMenuImage($menu_item['id']),
// 'image_url_compressed' => getMenuImage($menu_item['id'])
];
}
}
}
if($promo_setting['filter_type'] == 'category'){
foreach($promo_setting['free_item'] as $free_item_id){
$menu_items = $this->menuItemCategories
->select('menu_items.id, menu_items.title, menu_item_categories.category_id')
->join('menu_items', 'menu_items.id = menu_item_categories.menu_item_id')
->where('menu_item_categories.category_id', $free_item_id)
->where('menu_items.status', 'active')
->findAll();
if($menu_items){
foreach($menu_items as $item){
$menu_item = $this->menuItem
->select('menu_items.id, menu_items.title, menu_images.image_url, menu_images.image_url_compressed')
->join('menu_images', 'menu_images.menu_item_id = menu_items.id', 'left')
->where('menu_items.status', 'active')
->find($item['id']);
if($menu_item){
$free_items[$item['category_id']][] = [
'id' => $menu_item['id'],
'category_id' => $item['category_id'],
'title' => $menu_item['title'],
'image_url' => getMenuImage($menu_item['id']),
// 'image_url_compressed' => getMenuImage($menu_item['id'])
];
}
}
}
}
}
$afterPromo['free_item_list'] = $free_items;
}
//promo available
$this->carts->update($cart_id, ['promo_code_id' => $promo['id'], 'customer_voucher_list_id' => 0]);
// $applyPromoCode = $this->calculate_service->calculateCartTotals($cart_id, $outlet_id, null, null, null, null, null, null, 'promo');
} else if(!empty($voucher_id)){
// use voucher
// please add in voucher_expiry_date
$customer_voucher = $this->customer_voucher_list
->select('customer_voucher_list.*, promo_settings.promo_setting')
->join('promo_settings', 'promo_settings.id = customer_voucher_list.promo_setting_id')
->where('customer_voucher_list.id', $voucher_id)
->first();
if(empty($customer_voucher)){
return $this->respond(['status' => 400, 'result' => 'Voucher not found.']);
}
$promoSettingData = json_decode($customer_voucher['promo_setting'], true);
$promo_setting = $promoSettingData['Promo'];
// print_r($promo);exit;
//check voucher availability
$check_voucher = $this->voucher_service->checkVoucherAvailability($customer_voucher['id'], $order_type, $customer_id);
//voucher unavailable
if(isset($check_voucher['status']) && $check_voucher['status'] == 400) {
return $this->respond($check_voucher);
}
$free_items = [];
if($promo_setting['promo_type'] == 'free_item'){
$isIncluded = true;
if($promo_setting['filter_type'] == 'item'){
foreach($promo_setting['free_item'] as $free_item_id){
$menu_item = $this->menuItem
->select('menu_items.id, menu_items.title, menu_images.image_url, menu_images.image_url_compressed')
->join('menu_images', 'menu_images.menu_item_id = menu_items.id', 'left')
->where('menu_items.status', 'active')
->find($free_item_id);
if($menu_item){
$free_items[] = [
'id' => $menu_item['id'],
'title' => $menu_item['title'],
'image_url' => getMenuImage($menu_item['id']),
// 'image_url_compressed' => getMenuImage($menu_item['id'])
];
}
}
}
if($promo_setting['filter_type'] == 'category'){
foreach($promo_setting['free_item'] as $free_item_id){
$menu_items = $this->menuItemCategories
->select('menu_items.id, menu_items.title, menu_item_categories.category_id')
->join('menu_items', 'menu_items.id = menu_item_categories.menu_item_id')
->where('menu_item_categories.category_id', $free_item_id)
->where('menu_items.status', 'active')
->findAll();
if($menu_items){
foreach($menu_items as $item){
$menu_item = $this->menuItem
->select('menu_items.id, menu_items.title, menu_images.image_url, menu_images.image_url_compressed')
->join('menu_images', 'menu_images.menu_item_id = menu_items.id', 'left')
->where('menu_items.status', 'active')
->find($item['id']);
if($menu_item){
$free_items[$item['category_id']][] = [
'id' => $menu_item['id'],
'category_id' => $item['category_id'],
'title' => $menu_item['title'],
'image_url' => getMenuImage($menu_item['id']),
// 'image_url_compressed' => getMenuImage($menu_item['id'])
];
}
}
}
}
}
}
//voucher available
$this->carts->update($cart_id, ['customer_voucher_list_id' => $customer_voucher['id'], 'promo_code_id' => 0]);
// $applyPromoCode = $this->calculate_service->calculateCartTotals($cart_id, $outlet_id, null, null, null, null, null, null, 'voucher');
}
return $this->respond(['status' => 200, 'result' => 'Voucher applied successfully.', 'data' => $free_items]);
}
public function removeVoucher($customer_id)
{
$cart_id = $this->request->getVar('cart_id');
if(empty($cart_id)){
return $this->respond(['status' => 400, 'result' => 'Cart id is empty.']);
}
$getCart = $this->carts->where('customer_id', $customer_id)->where('status', 'active')->find($cart_id);
if(empty($getCart)) {
return $this->respond(['status' => 400, 'result' => 'Unable to find your cart.']);
}
$this->calculate_service->resetVoucher($cart_id);
return $this->respond(['status' => 200, 'result' => 'Voucher removed successfully.']);
}
}