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
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,274 @@
<?php
namespace App\Controllers\Backend;
use CodeIgniter\RESTful\ResourceController;
use App\Models\Orders;
use App\Models\TopupModel;
use App\Models\CustomerWallet;
use App\Models\CustomerVoucherList;
use App\Models\CustomerPoint;
use App\Models\LogCustomerCheckin; // Add LogCustomerCheckin model
class CustomerDashboardController extends ResourceController
{
private $orders;
private $topups;
private $wallets;
private $vouchers;
private $points;
private $checkins; // Add checkins model
public function __construct()
{
$this->orders = new Orders();
$this->topups = new TopupModel();
$this->wallets = new CustomerWallet();
$this->vouchers = new CustomerVoucherList();
$this->points = new CustomerPoint();
$this->checkins = new LogCustomerCheckin(); // Initialize checkins model
}
public function show($customerId = null)
{
if (!$customerId) {
return $this->fail('Customer ID is required', 400);
}
$orderSummary = $this->orders
->select('customer_id, COUNT(id) as total_orders, SUM(grand_total) as total_grand')
->where('customer_id', $customerId)
->groupBy('customer_id')
->first();
$topupSummary = $this->topups
->select('customer_id, COUNT(id) as total_topups, SUM(amount) as total_topup_amount')
->where('customer_id', $customerId)
->groupBy('customer_id')
->first();
$pointsSummary = $this->points
->select('customer_id,
COUNT(id) as total_point_transactions,
SUM(`in`) as total_point_in,
SUM(`out`) as total_point_out,
MAX(balance) as current_points')
->where('customer_id', $customerId)
->groupBy('customer_id')
->first();
$walletSummary = $this->wallets
->select('customer_id, SUM(`in`) as total_in, SUM(`out`) as total_out, MAX(balance) as current_balance')
->where('customer_id', $customerId)
->groupBy('customer_id')
->first();
$voucherSummary = $this->vouchers
->select('customer_id,
COUNT(id) as total_vouchers,
SUM(CASE WHEN voucher_status = "active" THEN 1 ELSE 0 END) as active_vouchers,
SUM(CASE WHEN voucher_status = "used" THEN 1 ELSE 0 END) as used_vouchers,
SUM(CASE WHEN voucher_status = "expired" THEN 1 ELSE 0 END) as expired_vouchers')
->where('customer_id', $customerId)
->groupBy('customer_id')
->first();
$activeVouchers = $this->vouchers
->where('customer_id', $customerId)
->where('voucher_status', 'active')
->where('voucher_expiry_date >=', date('Y-m-d H:i:s'))
->orderBy('voucher_expiry_date', 'ASC')
->findAll();
// Get check-in data
$checkinData = $this->checkins
->select('customer_id,
COUNT(id) as total_checkins,
MAX(streak_count) as highest_streak,
MAX(checkin_date) as last_checkin_date')
->where('customer_id', $customerId)
->groupBy('customer_id')
->first();
$recentCheckins = $this->checkins
->where('customer_id', $customerId)
->orderBy('checkin_date', 'DESC')
->limit(7) // Get last 7 check-ins
->findAll();
$orderLifecycle = $this->orders
->select('MIN(created_at) as first_order_date, MAX(created_at) as last_order_date')
->where('customer_id', $customerId)
->where('status !=', 'cancelled')
->first();
$topupLifecycle = $this->topups
->select('MIN(created_at) as first_topup_date, MAX(created_at) as last_topup_date')
->where('customer_id', $customerId)
->where('status', 'success')
->first();
$pointsLifecycle = $this->points
->select('MIN(created_at) as first_point_date, MAX(created_at) as last_point_date')
->where('customer_id', $customerId)
->first();
// Get check-in lifecycle
$checkinLifecycle = $this->checkins
->select('MIN(checkin_date) as first_checkin_date, MAX(checkin_date) as last_checkin_date')
->where('customer_id', $customerId)
->first();
$customerStatus = $this->calculateCustomerStatus($orderLifecycle, $topupLifecycle, $pointsLifecycle, $checkinLifecycle);
$lifecycleData = [
'first_activity' => $this->getEarliestDate([
$orderLifecycle['first_order_date'] ?? null,
$topupLifecycle['first_topup_date'] ?? null,
$pointsLifecycle['first_point_date'] ?? null,
$checkinLifecycle['first_checkin_date'] ?? null
]),
'last_activity' => $this->getLatestDate([
$orderLifecycle['last_order_date'] ?? null,
$topupLifecycle['last_topup_date'] ?? null,
$pointsLifecycle['last_point_date'] ?? null,
$checkinLifecycle['last_checkin_date'] ?? null
]),
'first_order' => $orderLifecycle['first_order_date'] ?? null,
'last_order' => $orderLifecycle['last_order_date'] ?? null,
'first_topup' => $topupLifecycle['first_topup_date'] ?? null,
'last_topup' => $topupLifecycle['last_topup_date'] ?? null,
'first_point' => $pointsLifecycle['first_point_date'] ?? null,
'last_point' => $pointsLifecycle['last_point_date'] ?? null,
'first_checkin' => $checkinLifecycle['first_checkin_date'] ?? null,
'last_checkin' => $checkinLifecycle['last_checkin_date'] ?? null,
'customer_status' => $customerStatus,
'days_since_last_activity' => $this->calculateDaysSinceLastActivity(
$orderLifecycle['last_order_date'] ?? null,
$topupLifecycle['last_topup_date'] ?? null,
$pointsLifecycle['last_point_date'] ?? null,
$checkinLifecycle['last_checkin_date'] ?? null
)
];
return $this->respond([
'status' => 200,
'message' => 'Customer dashboard data retrieved successfully',
'data' => [
'orders' => $orderSummary ?? [
'customer_id' => $customerId,
'total_orders' => 0,
'total_grand' => 0
],
'topups' => $topupSummary ?? [
'customer_id' => $customerId,
'total_topups' => 0,
'total_topup_amount' => 0
],
'points' => $pointsSummary ?? [
'customer_id' => $customerId,
'total_point_transactions' => 0,
'total_point_in' => 0,
'total_point_out' => 0,
'current_points' => 0
],
'wallet' => $walletSummary ?? [
'customer_id' => $customerId,
'total_in' => 0,
'total_out' => 0,
'current_balance' => 0
],
'vouchers' => [
'summary' => $voucherSummary ?? [
'customer_id' => $customerId,
'total_vouchers' => 0,
'active_vouchers' => 0,
'used_vouchers' => 0,
'expired_vouchers' => 0
],
'active_vouchers_list' => $activeVouchers
],
'checkins' => [ // Added checkins section
'summary' => $checkinData ?? [
'customer_id' => $customerId,
'total_checkins' => 0,
'highest_streak' => 0,
'last_checkin_date' => null
],
'recent_checkins' => $recentCheckins
],
'lifecycle' => $lifecycleData
]
]);
}
private function calculateCustomerStatus($orderLifecycle, $topupLifecycle, $pointsLifecycle, $checkinLifecycle)
{
$lastOrderDate = $orderLifecycle['last_order_date'] ?? null;
$lastTopupDate = $topupLifecycle['last_topup_date'] ?? null;
$lastPointDate = $pointsLifecycle['last_point_date'] ?? null;
$lastCheckinDate = $checkinLifecycle['last_checkin_date'] ?? null;
$lastActivity = $this->getLatestDate([$lastOrderDate, $lastTopupDate, $lastPointDate, $lastCheckinDate]);
if (!$lastActivity) {
return 'new';
}
$daysInactive = $this->calculateDaysSince($lastActivity);
if ($daysInactive <= 30) {
return 'active';
} elseif ($daysInactive <= 90) {
return 'dormant';
} else {
return 'churned';
}
}
private function calculateDaysSinceLastActivity($lastOrderDate, $lastTopupDate, $lastPointDate, $lastCheckinDate)
{
$lastActivity = $this->getLatestDate([$lastOrderDate, $lastTopupDate, $lastPointDate, $lastCheckinDate]);
if (!$lastActivity) {
return null;
}
return $this->calculateDaysSince($lastActivity);
}
private function calculateDaysSince($dateString)
{
if (!$dateString) {
return null;
}
$date = new \DateTime($dateString);
$now = new \DateTime();
$interval = $now->diff($date);
return $interval->days;
}
private function getEarliestDate(array $dates)
{
$validDates = array_filter($dates);
if (empty($validDates)) {
return null;
}
sort($validDates);
return $validDates[0];
}
private function getLatestDate(array $dates)
{
$validDates = array_filter($dates);
if (empty($validDates)) {
return null;
}
rsort($validDates);
return $validDates[0];
}
}
@@ -0,0 +1,278 @@
<?php
namespace App\Controllers\Backend;
use CodeIgniter\RESTful\ResourceController;
use App\Models\Orders;
use App\Models\TopupModel;
use App\Models\Customer;
use App\Models\Outlet;
class DashboardController extends ResourceController
{
private $orders;
private $topup;
private $customer;
private $outlets;
public function __construct()
{
$this->orders = new Orders();
$this->topup = new TopupModel();
$this->customer = new Customer();
$this->outlets = new Outlet();
}
public function dashboard()
{
$today = date('Y-m-d');
$month = date('m');
$year = date('Y');
// 1. Net Sales Today (sum of grand_total where paid)
$netSalesToday = $this->orders
->selectSum('grand_total')
->where('DATE(created_at)', $today)
->where('payment_status', 'paid')
->get()->getRow()->grand_total ?? 0;
// 2. Today Transaction (count orders today)
$todayTransaction = $this->orders
->where('DATE(created_at)', $today)
->where('payment_status', 'paid')
->countAllResults();
// 3. Net Sales Month to Date
$netSalesMonthToDate = $this->orders
->selectSum('grand_total')
->where('MONTH(created_at)', $month)
->where('YEAR(created_at)', $year)
->where('payment_status', 'paid')
->get()->getRow()->grand_total ?? 0;
// 4. Net Sales Year to Date
$netSalesYearToDate = $this->orders
->selectSum('grand_total')
->where('YEAR(created_at)', $year)
->where('payment_status', 'paid')
->get()->getRow()->grand_total ?? 0;
// 5. Topup
$topup1 = $this->topup
->selectSum('amount')
->where('DATE(created_at)', $today)
->where('status', 'Success')
->get()->getRow()->amount ?? 0;
$topup2 = $this->topup
->selectSum('other_amount')
->where('DATE(created_at)', $today)
->where('status', 'Success')
->get()->getRow()->other_amount ?? 0;
// 6. Total Customer Wallet Balance
$wallet_balance = $this->customer
->selectSum('customer_wallet')
->get()->getRow()->customer_wallet ?? 0;
// 7. Today Voucher Redeemed / Discount
$today_voucher_amount = $this->orders
->selectSum('voucher_discount_amount')
->where('DATE(created_at)', $today)
->where('payment_status', 'paid')
->get()->getRow()->voucher_discount_amount ?? 0;
$today_promo_amount = $this->orders
->selectSum('promo_discount_amount')
->where('DATE(created_at)', $today)
->where('payment_status', 'paid')
->get()->getRow()->promo_discount_amount ?? 0;
$today_discount_amount = $this->orders
->selectSum('promo_discount_amount')
->where('DATE(created_at)', $today)
->where('payment_status', 'paid')
->get()->getRow()->promo_discount_amount ?? 0;
$data = [
'today_net_sales' => $netSalesToday,
'today_total_transaction' => $todayTransaction,
'net_sales_month_to_date' => $netSalesMonthToDate,
'net_sales_year_to_date' => $netSalesYearToDate,
'today_topup' => $topup1 + $topup2,
'total_wallet_balance' => $wallet_balance,
'today_total_discount_amount' => $today_voucher_amount + $today_promo_amount + $today_discount_amount,
];
return $this->respond(['status' => 200, 'data' => $data]);
}
public function dashboardSummary ()
{
$data = [
'today' => $this->orders->getTodayOrdersRevenueByHour(),
'yesterday' => $this->orders->getYesterdayOrdersRevenueByHour(),
'last7days' => $this->orders->getLast7DaysOrdersRevenue(),
'last30days' => $this->orders->getLast30DaysOrdersRevenue(),
];
return $this->respond(['status' => 200, 'data' => $data]);
}
public function liveMonitor()
{
//Current Offline outlets
$outlets = $this->outlets->getOperatingHoursWithDaysList();
$onlineCount = 0;
$offlineCount = 0;
foreach ($outlets as $outlet) {
if ($this->isOutletOnline($outlet)) {
$onlineCount++;
} else {
$offlineCount++;
}
}
// Cancelled Orders (all time, or do you also want by date range?)
$cancelledOrders = $this->orders
->where('payment_status', 'cancelled')
->countAllResults();
// Dates
$endDateCurrent = date('Y-m-d'); // today
$startDateCurrent = date('Y-m-d', strtotime('-7 days')); // 7 days ago
$endDatePrevious = date('Y-m-d', strtotime('-8 days')); // day before current range
$startDatePrevious = date('Y-m-d', strtotime('-15 days')); // 15 days ago
// Function to fetch stats for a range
$getStats = function($startDate, $endDate) {
// Gross Sales
$grossSales = $this->orders
->selectSum('grand_total', 'gross_sales')
->where('payment_status', 'paid')
->where('created_at >=', $startDate)
->where('created_at <=', $endDate)
->where('promo_discount_amount <=', 0) // No promo discount
->where('voucher_discount_amount <=', 0) // No voucher discount
->where('discount_amount <=', 0) // No regular discount
->get()->getRow()->gross_sales ?? 0;
// Total Customer
$totalCustomer = $this->orders
->select('COUNT(DISTINCT customer_id) as total_customer')
->where('payment_status', 'paid')
->where('created_at >=', $startDate)
->where('created_at <=', $endDate)
->get()->getRow()->total_customer ?? 0;
// Net Sales from Offers
$netSalesOffers = $this->orders
->selectSum('grand_total', 'net_sales_offers')
->where('payment_status', 'paid')
->where('created_at >=', $startDate)
->where('created_at <=', $endDate)
->groupStart()
->where('promo_discount_amount >', 0)
->orWhere('voucher_discount_amount >', 0)
->orWhere('discount_amount >', 0)
->groupEnd()
->get()->getRow()->net_sales_offers ?? 0;
// Average Transaction
$avgTransaction = $this->orders
->selectAvg('grand_total', 'avg_transaction')
->where('payment_status', 'paid')
->where('created_at >=', $startDate)
->where('created_at <=', $endDate)
->get()->getRow()->avg_transaction ?? 0;
return [
'gross_sales' => $grossSales,
'total_customer' => $totalCustomer,
'net_sales_from_offers' => $netSalesOffers,
'avg_transaction' => $avgTransaction,
];
};
// Current 7 days
$current = $getStats($startDateCurrent, $endDateCurrent);
// Previous 7 days
$previous = $getStats($startDatePrevious, $endDatePrevious);
// Function to calculate percentage difference
$calcPercentage = function($currentValue, $previousValue) {
if ($previousValue == 0) {
return $currentValue > 0 ? 100 : 0;
}
return (($currentValue - $previousValue) / $previousValue) * 100;
};
$data = [
'offline_outlets' => $offlineCount,
'cancelled_orders' => $cancelledOrders,
'gross_sales' => [
'current' => $current['gross_sales'],
'previous' => $previous['gross_sales'],
'percentage' => $calcPercentage($current['gross_sales'], $previous['gross_sales']),
],
'total_customer' => [
'current' => $current['total_customer'],
'previous' => $previous['total_customer'],
'percentage' => $calcPercentage($current['total_customer'], $previous['total_customer']),
],
'net_sales_from_offers' => [
'current' => $current['net_sales_from_offers'],
'previous' => $previous['net_sales_from_offers'],
'percentage' => $calcPercentage($current['net_sales_from_offers'], $previous['net_sales_from_offers']),
],
'avg_transaction' => [
'current' => $current['avg_transaction'],
'previous' => $previous['avg_transaction'],
'percentage' => $calcPercentage($current['avg_transaction'], $previous['avg_transaction']),
],
];
return $this->respond(['status' => 200, 'data' => $data]);
}
private function isOutletOnline($outlet)
{
// Get current day and time
$currentDay = date('l'); // e.g., "Monday"
$currentTime = date('H:i:s'); // Current time in 24-hour format
// Check if outlet operates on current day
if (!isset($outlet['operating_schedule'][$currentDay]) ||
!$outlet['operating_schedule'][$currentDay]['is_operated']) {
return false;
}
$operatingHours = $outlet['operating_schedule'][$currentDay]['operating_hours'];
// Check if current time falls within any operating hour slot
foreach ($operatingHours as $timeSlot) {
$startTime = $timeSlot['start_time'];
$endTime = $timeSlot['end_time'];
// Handle cases where end time is 23:59:00 (which means until midnight)
if ($endTime === '23:59:00') {
$endTime = '23:59:59';
}
if ($currentTime >= $startTime && $currentTime <= $endTime) {
return true;
}
}
return false;
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace App\Controllers\Backend;
use App\Controllers\BaseController;
use App\Models\DeliverySettingModel;
use CodeIgniter\HTTP\ResponseInterface;
class DeliverySetting extends BaseController
{
protected $model;
public function __construct()
{
$this->model = new DeliverySettingModel();
}
public function index()
{
$data = $this->model->findAll();
// $this->model->orderBy('status', 'active');
return $this->response->setJSON([
'status' => 'success',
'data' => $data,
]);
}
public function create()
{
$data = $this->request->getJSON(true) ?? $this->request->getPost();
if (!$this->model->insert($data)) {
return $this->response->setStatusCode(ResponseInterface::HTTP_BAD_REQUEST)
->setJSON([
'status' => 'error',
'errors' => $this->model->errors(),
]);
}
return $this->response->setStatusCode(ResponseInterface::HTTP_CREATED)
->setJSON([
'status' => 'success',
'message' => 'Delivery setting created',
'data' => $this->model->find($this->model->getInsertID()),
]);
}
public function show($id = null)
{
$row = $this->model->find($id);
if (!$row) {
return $this->response->setStatusCode(ResponseInterface::HTTP_NOT_FOUND)
->setJSON(['status' => 'error', 'message' => 'Not found']);
}
return $this->response->setJSON([
'status' => 'success',
'data' => $row,
]);
}
public function update($id = null)
{
$data = $this->request->getJSON(true) ?? $this->request->getRawInput();
if (!$this->model->find($id)) {
return $this->response->setStatusCode(ResponseInterface::HTTP_NOT_FOUND)
->setJSON(['status' => 'error', 'message' => 'Not found']);
}
if (!$this->model->update($id, $data)) {
return $this->response->setStatusCode(ResponseInterface::HTTP_BAD_REQUEST)
->setJSON([
'status' => 'error',
'errors' => $this->model->errors(),
]);
}
return $this->response->setJSON([
'status' => 'success',
'message' => 'Delivery setting updated',
'data' => $this->model->find($id),
]);
}
public function delete($id = null)
{
if (!$this->model->find($id)) {
return $this->response->setStatusCode(ResponseInterface::HTTP_NOT_FOUND)
->setJSON(['status' => 'error', 'message' => 'Not found']);
}
$this->model->delete($id);
return $this->response->setJSON([
'status' => 'success',
'message' => 'Delivery setting deleted',
]);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Controllers\Backend;
use App\Controllers\BaseController;
class Home extends BaseController
{
public function index(): string
{
return view('welcome_message');
}
}
+170
View File
@@ -0,0 +1,170 @@
<?php
namespace App\Controllers\Backend;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\API\ResponseTrait;
use App\Models\User;
use Firebase\JWT\JWT;
class LoginController extends BaseController
{
use ResponseTrait;
public function index()
{
$userModel = new User();
$username = $this->request->getVar('username');
$password = $this->request->getVar('password_hash');
$user = $userModel->where('username', $username)->first();
if(is_null($user)) {
return $this->failUnauthorized('Invalid username or password.');
}
$hashedPassword = md5($password);
if ($hashedPassword !== $user['password_hash']) {
return $this->failUnauthorized('Invalid username or password.');
}
$key = getenv('JWT_SECRET');
$iat = time(); // current timestamp value
$exp = $iat + 86400;
$payload = array(
"iss" => "Issuer of the JWT",
"aud" => "Audience that the JWT",
"sub" => "Subject of the JWT",
"iat" => $iat, //Time the JWT issued at
"exp" => $exp, // Expiration time of token
"username" => $user['username'],
);
$token = JWT::encode($payload, $key, 'HS256');
$userData = [
'user_id' => $user['id'],
'username' => $user['username'],
'name' => $user['name'],
'role' => $user['role'],
'status'=> $user['status'],
'outlet_id'=> $user['outlet_id'],
// 'created_by'=> $user['created_by'],
'updated_at' => $user['updated_at'],
'created_at' => $user['created_at'],
];
$response = [
'message' => 'Login Succesful',
'token' => $token,
'userData' => $userData
];
// session()->set('merchant_id', $user['merchant_id']);
return $this->respond($response, 200);
}
public function requestToken()
{
$userModel = new User();
$merchant = $this->request->getVar('merchant');
$token_key = $this->request->getVar('token_key');
$user = $userModel->where('username', $merchant)->first();
if(is_null($user)) {
return $this->failUnauthorized('Invalid username.');
}
if ($token_key !== $user['token_key']) {
return $this->failUnauthorized('Invalid token key.');
}
$key = getenv('JWT_SECRET');
$iat = time(); // current timestamp value
$exp = $iat + 86400;
$payload = array(
"iss" => "Issuer of the JWT",
"aud" => "Audience that the JWT",
"sub" => "Subject of the JWT",
"iat" => $iat, //Time the JWT issued at
"exp" => $exp, // Expiration time of token
"user_id" => $user['user_id'],
"token_key" => $token_key,
);
$token = JWT::encode($payload, $key, 'HS256');
$response = [
'message' => 'Request Succesfully',
'token' => $token,
'expires' => date('Y-m-d H:i:s', $exp)
];
return $this->respond($response, 200);
}
/**
* Return the properties of a resource object
*
* @return mixed
*/
public function show($id = null)
{
//
}
/**
* Return a new resource object, with default properties
*
* @return mixed
*/
public function new()
{
//
}
/**
* Create a new resource object, from "posted" parameters
*
* @return mixed
*/
public function create()
{
//
}
/**
* Return the editable properties of a resource object
*
* @return mixed
*/
public function edit($id = null)
{
//
}
/**
* Add or update a model resource, from "posted" properties
*
* @return mixed
*/
public function update($id = null)
{
//
}
/**
* Delete the designated resource object from the model
*
* @return mixed
*/
public function delete($id = null)
{
//
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,248 @@
<?php
namespace App\Controllers\Backend;
use App\Models\Options;
use App\Models\OptionsGroups;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
helper('image');
class OptionController extends ResourceController
{
private $options;
private $option_groups;
public function __construct()
{
$this->options = new Options();
$this->option_groups = new OptionsGroups();
}
public function index()
{
// echo(123);exit;
$groups = $this->option_groups->findAll();
$data = [];
foreach ($groups as $group) {
$group['options'] = $this->options
->where('option_group_id', $group['id'])
->findAll();
$data[] = $group;
}
return $this->respond(['status' => 200, 'data' => $data]);
}
public function show($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'])
->findAll();
return $this->respond(['status' => 200, 'data' => $group]);
}
public function create()
{
$validation = $this->validate([
'title' => 'required',
'min_quantity' => 'permit_empty|integer',
'max_quantity' => 'permit_empty|integer',
'is_required' => 'required',
'status' => 'required',
'order_index' => 'permit_empty|integer',
'options' => 'permit_empty',
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$groupData = [
'title' => $this->request->getVar('title'),
'min_quantity' => $this->request->getVar('min_quantity') ?? 0,
'max_quantity' => $this->request->getVar('max_quantity') ?? 0,
'is_required' => $this->request->getVar('is_required'),
'status' => $this->request->getVar('status'),
'order_index' => $this->request->getVar('order_index') ?? 0,
];
$groupId = $this->option_groups->insert($groupData);
if (!$groupId) {
return $this->fail("Failed to create group.", 400);
}
// echo '<pre>';
// print_r($this->request->getPost());
// exit;
$options = $this->request->getJSON(true)['options'] ?? $this->request->getVar('options') ?? [];
if (!is_array($options)) {
return $this->failValidationErrors('Options not formatted correctly.');
}
$savedOptions = [];
foreach ($options as $i => $opt) {
$imageUrl = null;
$compressedUrl = null;
$imageFile = $this->request->getFile("image$i");
if ($imageFile && $imageFile->isValid() && !$imageFile->hasMoved()) {
$result = save_image_with_compression(
$imageFile,
FCPATH . 'backend/uploads/options',
FCPATH . 'backend/uploads/options_compressed',
900,
80
);
$imageUrl = base_url('backend/uploads/options' . basename($result['original']));
$compressedUrl = base_url('backend/uploads/options_compressed' . basename($result['compressed']));
}
$optionData = [
'option_group_id' => $groupId,
'title' => isset($opt['title']) ? $opt['title'] : '',
'price_adjustment' => isset($opt['price_adjustment']) ? $opt['price_adjustment'] : 0,
'order_index' => isset($opt['order_index']) ? $opt['order_index'] : $i,
'images' => $imageUrl,
'images_compressed' => $compressedUrl,
];
$this->options->insert($optionData);
$savedOptions[] = $optionData;
}
return $this->respond([
'status' => 200,
'message' => 'Group with options created.',
'data' => [
'group_id' => $groupId,
'group' => $groupData,
'options' => $savedOptions
]
]);
}
public function update($id = null)
{
$group = $this->option_groups->find($id);
if (!$group) {
return $this->fail("Group not found.", 400);
}
$validation = $this->validate([
'title' => 'required',
'min_quantity' => 'permit_empty|integer',
'max_quantity' => 'permit_empty|integer',
'is_required' => 'required|in_list[0,1,true,false]',
'status' => 'required',
'order_index' => 'permit_empty|integer',
'options' => 'permit_empty'
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$updateData = [
'title' => $this->request->getVar('title'),
'min_quantity' => $this->request->getVar('min_quantity') ?? 0,
'max_quantity' => $this->request->getVar('max_quantity') ?? 0,
'is_required' => $this->request->getVar('is_required'),
'status' => $this->request->getVar('status'),
'order_index' => $this->request->getVar('order_index') ?? 0,
];
$this->option_groups->update($id, $updateData);
$options = $this->request->getVar('options') ?? [];
$exist_option = $this->options->where('option_group_id', $id)->findAll();
$exist_option_group = array_column($exist_option, 'id');
$update_option_group = [];
foreach ($options as $i => $opt) {
$title = is_array($opt) ? $opt['title'] ?? '' : $opt->title ?? '';
$price = is_array($opt) ? $opt['price_adjustment'] ?? 0 : $opt->price_adjustment ?? 0;
$order = is_array($opt) ? $opt['order_index'] ?? 0 : $opt->order_index ?? 0;
$optId = is_array($opt) ? $opt['id'] ?? null : $opt->id ?? null;
$optionData = [
'option_group_id' => $id,
'title' => $title,
'price_adjustment' => $price,
'order_index' => $order,
'images' => $opt['images'] ?? null,
'images_compressed' => $opt['images_compressed'] ?? null,
];
$imageUrl = null;
$compressedUrl = null;
$imageFile = $this->request->getFile("image$i");
if ($imageFile && $imageFile->isValid() && !$imageFile->hasMoved()) {
$result = save_image_with_compression(
$imageFile,
FCPATH . 'backend/uploads/options/',
FCPATH . 'backend/uploads/options_compressed/',
900,
80
);
$imageUrl = base_url('backend/uploads/options/' . basename($result['original']));
$compressedUrl = base_url('backend/uploads/options_compressed/' . basename($result['compressed']));
}
if ($imageUrl) {
$optionData['images'] = $imageUrl;
$optionData['images_compressed'] = $compressedUrl;
}
if (!isset($opt->id)) {
$this->options->insert($optionData);
} else {
$this->options->update($opt->id, $optionData);
$update_option_group[] = $opt->id;
}
}
foreach ($exist_option_group as $option_id) {
if (!in_array($option_id, $update_option_group)) {
$this->options->delete($option_id);
}
}
return $this->respond(['status' => 200, 'message' => 'Group updated.']);
}
public function delete($id = null)
{
$group = $this->option_groups->find($id);
if (!$group) {
return $this->failNotFound("Group not found.");
}
$this->option_groups->delete($id);
$this->options->where('option_group_id', $id)->delete();
return $this->respond(['status' => 200, 'message' => 'Group and options deleted.']);
}
}
+581
View File
@@ -0,0 +1,581 @@
<?php
namespace App\Controllers\Backend;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use App\Models\OrderItemOptions;
use App\Models\OrderItems;
use App\Models\OrderPayments;
use App\Models\Orders;
use App\Models\OrderTaxes;
use CodeIgniter\Database\Config;
use CodeIgniter\HTTP\Message;
use App\Models\OrderDeliveries;
use App\Libraries\Wato;
use App\Models\User;
use App\Models\MenuItemVariations;
class OrderController extends ResourceController
{
private $orders;
private $order_items;
private $order_item_options;
private $order_payments;
private $order_taxes;
private $order_deliveries;
private $db;
private $wato;
private $user;
private $menu_item_variations;
public function __construct()
{
$this->orders = new Orders();
$this->order_items = new OrderItems();
$this->order_item_options = new OrderItemOptions();
$this->order_taxes = new OrderTaxes();
$this->order_payments = new OrderPayments();
$this->order_deliveries = new OrderDeliveries();
$this->db = Config::connect();
$this->wato = new Wato();
$this->user = new User();
$this->menu_item_variations = new MenuItemVariations();
}
public function orderList()
{
$user_id = $this->request->getVar('user_id');
$start_date = $this->request->getVar('start_date');
$end_date = $this->request->getVar('end_date');
$status = $this->request->getVar('status');
$outlet_id = $this->request->getVar('outlet_id');
$order_type = $this->request->getVar('order_type');
// Get the user information to check role and outlet
$user = $this->user->find($user_id);
if (!$user) {
return $this->respond([
'status' => 404,
'message' => 'User not found',
'data' => []
]);
}
$orderQuery = $this->orders
->orderBy('created_at', 'DESC');
// If user is not admin, filter by their outlet_id
if ($user['role'] !== 'admin') {
$orderQuery->where('outlet_id', $user['outlet_id']);
} else {
// If admin and specific outlet_id is provided, use it
if (!empty($outlet_id)) {
$orderQuery->where('outlet_id', $outlet_id);
}
// Otherwise admin sees all orders (no outlet filter)
}
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($outlet_id)) {
$orderQuery->where('outlet_id', $outlet_id);
}
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!',
'data' => []
]);
}
foreach ($orders as &$order) {
$order_id = $order['id'];
// Fetch items + options
$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();
}
// Fetch taxes
$order['taxes'] = $this->order_taxes
->where('order_id', $order_id)
->findAll();
// Fetch payments
$order['payments'] = $this->order_payments
->where('order_id', $order_id)
->orderBy('created_at', 'DESC')
->findAll();
// Fetch deliveries
$order['deliveries'] = $this->order_deliveries
->where('order_id', $order_id)
->findAll();
}
return $this->respond([
'status' => 200,
'message' => 'Orders retrieved successfully',
'data' => $orders
]);
}
public function showOrder($order_id = null)
{
// Get order with customer + outlet info
$order = $this->orders
->select('
orders.*,
customers.id as customer_id,
customers.name as customer_name,
customers.email as customer_email,
customers.phone as customer_phone,
customers.profile_picture as customer_profile_pic,
outlets.id as outlet_id,
outlets.title as outlet_title,
outlets.email as outlet_email,
outlets.phone as outlet_phone,
outlets.address as outlet_address,
')
->join('customers', 'customers.id = orders.customer_id', 'left')
->join('outlets', 'outlets.id = orders.outlet_id', 'left') // join outlets
->where('orders.id', $order_id)
->first();
if (!$order) {
return $this->fail('Order not found', 400);
}
// Items + options + menu images
$order['items'] = $this->order_items
->select('order_items.*, menu_images.image_url as menu_item_image')
->join('menu_images', 'menu_images.menu_item_id = order_items.menu_item_id', 'left')
->where('order_items.order_id', $order_id)
->groupBy('order_items.id')
->findAll();
foreach ($order['items'] as &$item) {
$item['options'] = $this->order_item_options->where('order_item_id', $item['id'])->findAll();
$item['menu_item_image'] = getMenuImage($item['menu_item_id']);
$item['variation_name'] = $this->menu_item_variations
->where('menu_item_id', $item['menu_item_id'])
->where('id', $item['variation_id'])
->first()['title'] ?? '';
}
// Taxes
$order['taxes'] = $this->order_taxes->where('order_id', $order_id)->findAll();
// Payments
$order['payments'] = $this->order_payments
->where('order_id', $order_id)
->orderBy('created_at', 'DESC')
->findAll();
// Deliveries
$order['deliveries'] = $this->order_deliveries->where('order_id', $order_id)->findAll();
return $this->respond([
'status' => 200,
'message' => 'Order retrieved successfully',
'data' => $order
]);
}
public function updateOrderSchedule($order_id = null)
{
// Validate order_id
if (empty($order_id)) {
return $this->fail('Order ID is required', 400);
}
// Get the order
$order = $this->orders->find($order_id);
if (!$order) {
return $this->fail('Order not found', 404);
}
// Check if order status is 'complete'
if (isset($order['status']) && $order['status'] === 'complete') {
return $this->fail('Cannot modify schedule for completed orders', 400);
}
// Get request data
$selected_date = $this->request->getVar('selected_date');
$selected_time = $this->request->getVar('selected_time');
// Validate input
if (empty($selected_date) || empty($selected_time)) {
return $this->fail('Both selected_date and selected_time are required', 400);
}
// Prepare data to update
$data = [
'selected_date' => $selected_date,
'selected_time' => $selected_time,
'updated_at' => date('Y-m-d H:i:s') // Update timestamp
];
try {
// Update the order
$updated = $this->orders->update($order_id, $data);
if (!$updated) {
return $this->fail('Failed to update order schedule', 500);
}
// Get the updated order
$updatedOrder = $this->orders->find($order_id);
return $this->respond([
'status' => 200,
'message' => 'Order schedule updated successfully',
'data' => $updatedOrder
]);
} catch (\Exception $e) {
return $this->fail('An error occurred while updating order schedule: ' . $e->getMessage(), 500);
}
}
public function updateOrderStatus($order_id = null)
{
// Validate order_id
if (empty($order_id)) {
return $this->fail('Order ID is required', 400);
}
// Get the order
$order = $this->orders->select('orders.*, customer_addresses.phone as recipient_phone')
->join('customer_addresses', 'customer_addresses.id = orders.customer_address_id AND customer_addresses.deleted_at IS NULL', 'left')->find($order_id);
if (!$order) {
return $this->fail('Order not found', 404);
}
// Get request data
$status = $this->request->getVar('status');
// Validate input
if (empty($status)) {
return $this->fail('Status is required', 400);
}
// Define allowed status values
$allowedStatuses = ['pending', 'picked_up', 'on_the_way', 'completed', 'ready_to_pickup'];
if (!in_array($status, $allowedStatuses)) {
return $this->fail('Invalid status value. Allowed values: ' . implode(', ', $allowedStatuses), 400);
}
// Prepare data to update
$data = [
'status' => $status,
'updated_at' => date('Y-m-d H:i:s') // Update timestamp
];
try {
// Update the order
$updated = $this->orders->update($order_id, $data);
if ($order['status'] != $status) { //send notification to customer if status is changed
$message = '';
switch ($status) {
case 'ready_to_pickup':
$message = "🍴 Your food is ready for pickup!\nPlease show your order number at the counter: \n**{{" . $order['order_so'] . "}}**";
break;
case 'on_the_way':
$message = "🚚 Your order [**" . $order['order_so'] . "**] is on the way!\nThe driver is delivering your food now.\nPlease get ready to receive it.";
break;
case 'completed':
$message = "🎉 Your order [**" . $order['order_so'] . "**] has been completed.\nWe hope you enjoy your meal!\nThank you for ordering with us.";
break;
}
if ($message) {
$this->wato->pushNotification($order['recipient_phone'], $message);
}
}
if (!$updated) {
return $this->fail('Failed to update order status', 500);
}
// Get the updated order
$updatedOrder = $this->orders->find($order_id);
return $this->respond([
'status' => 200,
'message' => 'Order status updated successfully',
'data' => $updatedOrder
]);
} catch (\Exception $e) {
return $this->fail('An error occurred while updating order status: ' . $e->getMessage(), 500);
}
}
public function createOrderDelivery()
{
// Get request data
$order_id = $this->request->getVar('order_id');
$fee_amount = $this->request->getVar('actual_fee_amount');
$tracking_link = $this->request->getVar('tracking_link');
// Optional fields that will be set to empty string if not provided
$provider_name = $this->request->getVar('provider_name') ?? '';
$provider_order_id = $this->request->getVar('provider_order_id') ?? '';
$actual_fee_amount = $this->request->getVar('fee_amount') ?? '';
$transaction_id = $this->request->getVar('transaction_id') ?? '';
// Validate required fields
if (empty($order_id) || empty($actual_fee_amount) || empty($tracking_link)) {
return $this->fail('order_id, actual_fee_amount, and tracking_link are required', 400);
}
// Check if the order exists
$order = $this->orders->find($order_id);
if (!$order) {
return $this->fail('Order not found', 404);
}
// Prepare data for insertion with empty strings for optional fields
$data = [
'order_id' => $order_id,
'provider_name' => $provider_name,
'status' => 'pending', // Default status
'provider_order_id' => $provider_order_id,
'fee_amount' => $fee_amount,
'actual_fee_amount' => $actual_fee_amount,
'transaction_id' => $transaction_id,
'tracking_link' => $tracking_link,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
];
try {
// Insert the data
$inserted = $this->order_deliveries->insert($data);
if (!$inserted) {
return $this->fail('Failed to create order delivery record', 500);
}
// Get the inserted ID
$insertId = $this->db->insertID();
// Return success response with the created record
return $this->respond([
'status' => 201,
'message' => 'Order delivery record created successfully',
'data' => array_merge(['id' => $insertId], $data)
], 201);
} catch (\Exception $e) {
return $this->fail('An error occurred while creating order delivery: ' . $e->getMessage(), 500);
}
}
public function updateOrderDelivery($id = null)
{
if (empty($id)) {
return $this->fail('Delivery record ID is required', 400);
}
// Get request data - all fields optional except id
$data = [
'actual_fee_amount' => $this->request->getVar('actual_fee_amount') ?? '',
'tracking_link' => $this->request->getVar('tracking_link'),
'updated_at' => date('Y-m-d H:i:s')
];
// Remove fields that weren't provided in the request (except status which has a default)
$data = array_filter($data, function ($value, $key) {
return $value !== null || $key === 'status';
}, ARRAY_FILTER_USE_BOTH);
if (empty($data)) {
return $this->respond([
'status' => 200,
'message' => 'No fields to update',
'data' => null
]);
}
try {
$updated = $this->order_deliveries->update($id, $data);
if (!$updated) {
return $this->fail('Failed to update order delivery record', 500);
}
// Get the updated record
$updatedData = $this->order_deliveries->find($id);
// Convert NULL values to empty strings in the response
$responseData = [
'id' => $id,
'order_id' => $updatedData['order_id'],
'provider_name' => $updatedData['provider_name'] ?? '',
'status' => $updatedData['status'] ?? '',
'provider_order_id' => $updatedData['provider_order_id'] ?? '',
'fee_amount' => $updatedData['fee_amount'] ?? '',
'actual_fee_amount' => $updatedData['actual_fee_amount'],
'transaction_id' => $updatedData['transaction_id'] ?? '',
'tracking_link' => $updatedData['tracking_link'],
'created_at' => $updatedData['created_at'],
'updated_at' => $updatedData['updated_at']
];
return $this->respond([
'status' => 200,
'message' => 'Order delivery updated successfully',
'data' => $responseData
]);
} catch (\Exception $e) {
return $this->fail('An error occurred while updating order delivery: ' . $e->getMessage(), 500);
}
}
public function getOrderDelivery($order_id = null)
{
// Validate order_id
if (empty($order_id)) {
return $this->fail('Order ID is required', 400);
}
try {
// Get delivery record by order_id
$delivery = $this->order_deliveries->where('order_id', $order_id)->get()->getRowArray();
if (!$delivery) {
return $this->respond([
'status' => 404,
'message' => 'No delivery record found for this order',
'data' => null
], 404);
}
// Format the response data with empty strings instead of NULL
$responseData = [
'id' => $delivery['id'],
'order_id' => $delivery['order_id'],
'provider_name' => $delivery['provider_name'] ?? '',
'status' => $delivery['status'] ?? '',
'provider_order_id' => $delivery['provider_order_id'] ?? '',
'fee_amount' => $delivery['fee_amount'] ?? '',
'actual_fee_amount' => $delivery['actual_fee_amount'],
'transaction_id' => $delivery['transaction_id'] ?? '',
'tracking_link' => $delivery['tracking_link'],
'created_at' => $delivery['created_at'],
'updated_at' => $delivery['updated_at']
];
return $this->respond([
'status' => 200,
'message' => 'Order delivery retrieved successfully',
'data' => $responseData
]);
} catch (\Exception $e) {
return $this->fail('An error occurred while fetching order delivery: ' . $e->getMessage(), 500);
}
}
public function customerOrderList()
{
$start_date = $this->request->getVar('start_date');
$end_date = $this->request->getVar('end_date');
$status = $this->request->getVar('status');
$outlet_id = $this->request->getVar('outlet_id');
$order_type = $this->request->getVar('order_type');
$orderQuery = $this->orders
->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($outlet_id)) {
$orderQuery->where('outlet_id', $outlet_id);
}
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!',
'data' => []
]);
}
foreach ($orders as &$order) {
$order_id = $order['id'];
// Fetch items + options
$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();
}
// Fetch taxes
$order['taxes'] = $this->order_taxes
->where('order_id', $order_id)
->findAll();
// Fetch payments
$order['payments'] = $this->order_payments
->where('order_id', $order_id)
->orderBy('created_at', 'DESC')
->findAll();
// Fetch deliveries
$order['deliveries'] = $this->order_deliveries
->where('order_id', $order_id)
->findAll();
}
return $this->respond([
'status' => 200,
'message' => 'Orders retrieved successfully',
'data' => $orders
]);
}
}
@@ -0,0 +1,863 @@
<?php
namespace App\Controllers\Backend;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use App\Models\Outlet;
use App\Models\OutletTax;
use App\Models\OutletImage;
use App\Models\OutletOperatingDay;
use App\Models\OutletOperatingHour;
use App\Models\OutletOperatingHoursException;
use App\Models\SettingTax;
use App\Models\OutletMenus;
use App\Models\MenuItems;
use App\Models\User;
helper('image');
class OutletController extends ResourceController
{
private $outlet;
private $outletTax;
private $outletImage;
private $outletOperatingDays;
private $outletOperatingHours;
private $outletOperatingHoursExceptions;
private $settingTax;
private $outlet_menu;
private $menu_items;
private $user;
protected $db;
public function __construct()
{
$this->outlet = new Outlet();
$this->outletTax = new OutletTax();
$this->outletImage = new OutletImage();
$this->outletOperatingDays = new OutletOperatingDay();
$this->outletOperatingHours = new OutletOperatingHour();
$this->outletOperatingHoursExceptions = new OutletOperatingHoursException();
$this->settingTax = new SettingTax();
$this->db = \Config\Database::connect();
$this->outlet_menu = new OutletMenus();
$this->menu_items = new MenuItems();
$this->user = new User();
}
public function index()
{
$user_id = $this->request->getVar('user_id');
if(!empty($user_id)){
$user = $this->user->find($user_id);
if($user['role'] == 'outlet'){
$outlets = $this->outlet->getOperatingHoursWithDaysList($user['outlet_id']);
} else {
$outlets = $this->outlet->getOperatingHoursWithDaysList();
}
} else {
return $this->respond (['status' => 400, 'result'=> 'User Id is required.']);
}
if(empty($outlets)){
return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
}
return $this->respond(['status' => 200, 'result' => $outlets]);
}
public function show($id = null)
{
$outlet = $this->outlet->getOperatingHoursWithDays($id);
if(empty($outlet)){
return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
}
return $this->respond(['status' => 200, 'result' => $outlet]);
}
public function create()
{
$validationRules = [
'title' => 'required',
'email' => 'required',
'phone' => 'required',
'address' => 'required',
'state' => 'required',
'postal_code' => 'required',
'country' => 'required',
'latitude' => 'required|numeric',
'longitude' => 'required|numeric',
'password' => 'required|min_length[8]',
'outlet_delivery_coverage' => 'required|numeric',
'outlet_tax' => 'permit_empty',
'outlet_operating_days' => 'permit_empty',
'outlet_operating_hours' => 'permit_empty',
'outlet_operating_hours_exceptions' => 'permit_empty',
];
$validation = $this->validate($validationRules);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
// Start database transaction
$this->db->transBegin();
try {
$outletData = [
"title" => $this->request->getVar('title'),
"email" => $this->request->getVar('email'),
"phone" => $this->request->getVar('phone'),
"address" => $this->request->getVar('address'),
"state" => $this->request->getVar('state'),
"postal_code" => $this->request->getVar('postal_code'),
"country" => $this->request->getVar('country'),
"status" => $this->request->getVar('status'),
"latitude" => $this->request->getVar('latitude'),
"longitude" => $this->request->getVar('longitude'),
"password" => md5(md5($this->request->getVar('password'))),
"serve_method" => $this->request->getVar('serve_method'),
"delivery_options" => $this->request->getVar('delivery_options'),
"outlet_delivery_coverage" => $this->request->getVar('outlet_delivery_coverage'),
"order_max_per_hour" => $this->request->getVar('order_max_per_hour'),
"item_max_per_hour" => $this->request->getVar('item_max_per_hour'),
"menu_item" => json_encode($this->request->getVar('outlet_menu')),
];
$id = $this->outlet->insert($outletData);
if (!$id) {
throw new \RuntimeException('Failed to insert outlet data');
}
$outlet_menu = $this->request->getVar('outlet_menu');
if(!empty($outlet_menu)){
foreach($outlet_menu as $menu){
$outletMenuItem = [
"outlet_id" => $id,
"menu_item_id" => $menu,
];
if (!$this->outlet_menu->insert($outletMenuItem)) {
throw new \RuntimeException('Failed to insert outlet tax data');
}
}
}
// Process taxes
$tax_ids = $this->request->getVar('outlet_tax');
if(!empty($tax_ids)){
foreach ($tax_ids as $tax_id) {
$outletTaxData = [
"outlet_id" => $id,
"tax_id" => $tax_id,
];
if (!$this->outletTax->insert($outletTaxData)) {
throw new \RuntimeException('Failed to insert outlet tax data');
}
}
}
// Process images
$images = $this->request->getFiles('outlet_images');
$outlet_images = [];
if (!empty($images['outlet_images'])) {
foreach ($images['outlet_images'] as $index => $image) {
if (empty($image) || !$image->isValid() || $image->hasMoved()) {
continue;
}
try {
$result = save_image_with_compression(
$image,
FCPATH . 'backend/uploads/outlets',
FCPATH . 'backend/uploads/outlets_compressed',
900, // width
80 // quality
);
$originalFileName = basename($result['original']);
$compressedFileName = basename($result['compressed']);
if (!$this->outletImage->insert([
"outlet_id" => $id,
"image_url" => $originalFileName,
"compressed_image_url" => $compressedFileName,
"order_index" => $index
])) {
@unlink($result['original']);
@unlink($result['compressed']);
throw new \RuntimeException('Failed to insert outlet image data');
}
$outlet_images[$index] = [
'image_url' => $originalFileName,
'compressed_image_url' => $compressedFileName,
];
} catch (\Exception $e) {
log_message('error', 'Failed to upload and compress image: ' . $e->getMessage());
throw $e;
}
}
}
// Process operating days
$outlet_operating_days = json_decode($this->request->getVar('outlet_operating_days'), true);
$operating_days = [];
// print_r($this->request->getVar('outlet_operating_days'));exit;
if(!empty($outlet_operating_days[0])){
foreach ($outlet_operating_days[0] as $index => $day) {
$day_id = $this->outletOperatingDays->insert([
"outlet_id" => $id,
"day_of_week" => $index,
"is_operated" => $day['is_operated'],
]);
if (!$day_id) {
throw new \RuntimeException('Failed to insert operating days data');
}
$operating_days[$index] = [
'id' => $day_id,
"outlet_id" => $id,
"day_of_week" => $index,
"is_operated" => $day['is_operated'],
];
}
}
// Process operating hours
$outlet_operating_hours = json_decode($this->request->getVar('outlet_operating_hours'), true);
$operating_hours = [];
if(!empty($outlet_operating_hours[0])){
foreach ($outlet_operating_hours[0] as $index => $hours) {
foreach ($hours as $hour) {
$hour_id = $this->outletOperatingHours->insert([
"outlet_id" => $id,
"day_of_week" => $index,
"start_time" => $hour['start_time'],
"end_time" => $hour['end_time'],
]);
if (!$hour_id) {
throw new \RuntimeException('Failed to insert operating hours data');
}
$operating_hours[$index][] = [
'id' => $hour_id,
"outlet_id" => $id,
"day_of_week" => $index,
"start_time" => $hour['start_time'],
"end_time" => $hour['end_time'],
];
}
}
}
// Process operating hours exceptions
$outlet_operating_hours_exceptions = json_decode($this->request->getVar('outlet_operating_hours_exceptions'), true);
$operating_hours_exceptions = [];
if (!empty($outlet_operating_hours_exceptions)) {
foreach ($outlet_operating_hours_exceptions as $index => $exception) {
$hours_exception_id = $this->outletOperatingHoursExceptions->insert([
"outlet_id" => $id,
"date" => $exception['date'],
"start_time" => $exception['start_time'],
"end_time" => $exception['end_time'],
"notes" => $exception['notes'],
]);
if (!$hours_exception_id) {
throw new \RuntimeException('Failed to insert operating hours exceptions data');
}
$operating_hours_exceptions[$index] = [
'id' => $hours_exception_id,
"outlet_id" => $id,
"date" => $exception['date'],
"start_time" => $exception['start_time'],
"end_time" => $exception['end_time'],
"notes" => $exception['notes'],
];
}
}
// Commit transaction if everything succeeded
$this->db->transCommit();
$result = [
'id' => $id,
'title' => $this->request->getVar('title'),
'email' => $this->request->getVar('email'),
'phone' => $this->request->getVar('phone'),
'address' => $this->request->getVar('address'),
'state' => $this->request->getVar('state'),
'postal_code' => $this->request->getVar('postal_code'),
'country' => $this->request->getVar('country'),
'status' => $this->request->getVar('status'),
'latitude' => $this->request->getVar('latitude'),
'longitude' => $this->request->getVar('longitude'),
'password' => md5(md5($this->request->getVar('password'))),
'serve_method' => $this->request->getVar('serve_method'),
'delivery_options' => $this->request->getVar('delivery_options'),
'outlet_delivery_coverage' => $this->request->getVar('outlet_delivery_coverage'),
'order_max_per_hour' => $this->request->getVar('order_max_per_hour'),
'item_max_per_hour' => $this->request->getVar('item_max_per_hour'),
'outlet_tax' => $tax_ids,
'outlet_images' => $outlet_images,
'outlet_operating_days' => $operating_days,
'outlet_operating_hours' => $operating_hours,
'outlet_operating_hours_exceptions' => $operating_hours_exceptions ?? [],
'menu_item' => $this->request->getVar('outlet_menu'),
];
return $this->respond(['status' => 200, 'result' => $result]);
} catch (\Exception $e) {
// Rollback transaction on any error
$this->db->transRollback();
// Clean up any uploaded files if transaction fails
if (!empty($outlet_images)) {
$uploadPath = $_SERVER['DOCUMENT_ROOT'] . '/backend/uploads/outlets/';
foreach ($outlet_images as $image) {
@unlink($uploadPath . $image);
}
}
log_message('error', 'Outlet creation failed: ' . $e->getMessage());
return $this->failServerError('Failed to create outlet: ' . $e->getMessage());
}
}
public function update($id = null)
{
$outlet = $this->outlet->find($id);
if (empty($outlet)) {
return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
}
$validationRules = [
'title' => 'required',
'email' => 'required',
'phone' => 'required',
'address' => 'required',
'state' => 'required',
'postal_code' => 'required',
'country' => 'required',
'latitude' => 'required|numeric',
'longitude' => 'required|numeric',
'outlet_delivery_coverage' => 'required|numeric',
'outlet_tax' => 'permit_empty',
'outlet_operating_days' => 'permit_empty',
'outlet_operating_hours' => 'permit_empty',
'outlet_operating_hours_exceptions' => 'permit_empty',
'outlet_images' => 'permit_empty'
];
// Get all input data
$input = $this->request->getVar();
// Decode only the JSON fields
$jsonFields = [
'outlet_tax',
'outlet_operating_days',
'outlet_operating_hours',
'outlet_operating_hours_exceptions'
];
foreach ($jsonFields as $field) {
if (isset($input[$field]) && is_string($input[$field])) {
$input[$field] = json_decode($input[$field], true);
}
}
if (!$this->validateData($input, $validationRules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$outlet = $this->outlet->find($id);
if(empty($outlet)){
return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
}
// Prepare outlet data
$outlet_data = ['id' => $id];
$fields = [
'title', 'email', 'phone', 'address', 'state', 'postal_code', 'country',
'status', 'latitude', 'longitude', 'serve_method', 'delivery_options',
'outlet_delivery_coverage', 'order_max_per_hour', 'item_max_per_hour'
];
foreach ($fields as $field) {
if (isset($input[$field])) {
$outlet_data[$field] = $input[$field];
}
}
if (!empty($input['password']) && $input['password'] != 'null' && $input['password'] != '' && $input['password'] != 'undefined') {
$outlet_data['password'] = md5(md5($input['password']));
} else {
$outlet_data['password'] = $outlet['password'];
}
// print_r($outlet_data);exit;
// Start transaction
$this->db->transBegin();
try {
// Update main outlet data
$response = $this->outlet->save($outlet_data);
if (!$response) {
throw new \Exception('Failed to update outlet');
}
// Handle outlet taxes
if (isset($input['outlet_tax']) && is_array($input['outlet_tax'])) {
$existingTaxes = $this->outletTax->where('outlet_id', $id)
->where('deleted_at', null)
->findAll();
$existingTaxIds = array_column($existingTaxes, 'tax_id', 'id');
$updatedTaxIds = [];
foreach ($input['outlet_tax'] as $tax) {
$taxData = [
'outlet_id' => $id,
'tax_id' => $tax['tax_id'],
'updated_at' => date('Y-m-d H:i:s')
];
$taxId = array_search($tax['tax_id'], $existingTaxIds);
if ($taxId !== false) {
$taxData['id'] = $taxId;
$this->outletTax->save($taxData);
$updatedTaxIds[] = $taxId;
} else {
$taxData['created_at'] = date('Y-m-d H:i:s');
$newId = $this->outletTax->insert($taxData);
$updatedTaxIds[] = $newId;
}
}
// Soft delete removed taxes
foreach ($existingTaxes as $existingTax) {
if (!in_array($existingTax['id'], $updatedTaxIds)) {
$this->outletTax->where('id', $existingTax['id'])
->set(['deleted_at' => date('Y-m-d H:i:s')])
->update();
}
}
}
$images = $this->request->getFiles();
if (!empty($images['outlet_images'])) {
$images = $images['outlet_images'];
}
$existing_image = $this->request->getVar("existing_image");
if (!empty($images)) {
$exist_images = $this->outletImage->where('outlet_id', $id)->findAll();
$exist_images_group = array_column($exist_images, 'id');
foreach ($images as $image_file) {
if ($image_file && $image_file->isValid() && !$image_file->hasMoved()) {
$result = save_image_with_compression(
$image_file,
FCPATH . 'backend/uploads/outlets',
FCPATH . 'backend/uploads/outlets_compressed',
900, // width
80 // quality
);
$originalFileName = basename($result['original']);
$compressedFileName = basename($result['compressed']);
if (!$this->outletImage->insert([
'outlet_id' => $id,
'image_url' => $originalFileName,
'compressed_image_url' => $compressedFileName
])) {
throw new \Exception('Failed to update image!');
}
}
}
if (!empty($existing_image)) {
foreach ($exist_images_group as $image_id) {
if (!in_array($image_id, $existing_image)) {
$this->outletImage->delete($image_id);
}
}
}
}
// Handle operating days
if (isset($input['outlet_operating_days']) && is_array($input['outlet_operating_days'])) {
$operatingDays = $input['outlet_operating_days'][0];
$existingDays = $this->outletOperatingDays
->where('outlet_id', $id)
->findAll();
$existingDayMap = [];
foreach ($existingDays as $day) {
$existingDayMap[$day['day_of_week']] = $day;
}
$updatedDays = [];
foreach ($operatingDays as $dayName => $dayData) {
$dayOfWeek = ucfirst(strtolower($dayName));
$dayRecord = [
'outlet_id' => $id,
'day_of_week' => $dayOfWeek,
'is_operated' => $dayData['is_operated'],
'updated_at' => date('Y-m-d H:i:s')
];
if (isset($existingDayMap[$dayOfWeek])) {
$dayRecord['id'] = $existingDayMap[$dayOfWeek]['id'];
$this->outletOperatingDays->save($dayRecord);
$updatedDays[] = $dayOfWeek;
} else {
$dayRecord['created_at'] = date('Y-m-d H:i:s');
$this->outletOperatingDays->insert($dayRecord);
$updatedDays[] = $dayOfWeek;
}
}
// Soft delete removed days
foreach ($existingDays as $day) {
if (!in_array($day['day_of_week'], $updatedDays)) {
$this->outletOperatingDays->where('id', $day['id'])
->set(['deleted_at' => date('Y-m-d H:i:s')])
->update();
}
}
}
// Handle operating hours
if (isset($input['outlet_operating_hours']) && is_array($input['outlet_operating_hours'])) {
$operatingHours = $input['outlet_operating_hours'][0];
$existingHours = $this->outletOperatingHours
->where('outlet_id', $id)
->findAll();
$existingHoursByDay = [];
foreach ($existingHours as $hour) {
$existingHoursByDay[$hour['day_of_week']][] = $hour;
}
foreach ($operatingHours as $dayName => $timeSlots) {
$dayOfWeek = ucfirst(strtolower($dayName));
$updatedHourIds = [];
if (!empty($timeSlots)) {
foreach ($timeSlots as $slot) {
$hourRecord = [
'outlet_id' => $id,
'day_of_week' => $dayOfWeek,
'start_time' => $slot['start_time'],
'end_time' => $slot['end_time'],
'updated_at' => date('Y-m-d H:i:s')
];
$found = false;
if (isset($existingHoursByDay[$dayOfWeek])) {
foreach ($existingHoursByDay[$dayOfWeek] as $existingHour) {
if ($existingHour['start_time'] == $slot['start_time'] &&
$existingHour['end_time'] == $slot['end_time']) {
$hourRecord['id'] = $existingHour['id'];
$this->outletOperatingHours->save($hourRecord);
$updatedHourIds[] = $existingHour['id'];
$found = true;
break;
}
}
}
if (!$found) {
$hourRecord['created_at'] = date('Y-m-d H:i:s');
$newId = $this->outletOperatingHours->insert($hourRecord);
$updatedHourIds[] = $newId;
}
}
}
// Soft delete removed hours
if (isset($existingHoursByDay[$dayOfWeek])) {
foreach ($existingHoursByDay[$dayOfWeek] as $existingHour) {
if (!in_array($existingHour['id'], $updatedHourIds)) {
$this->outletOperatingHours
->where('id', $existingHour['id'])
->set(['deleted_at' => date('Y-m-d H:i:s')])
->update();
}
}
}
}
}
// Handle outlet menu items
// print_r($input);exit;
// print_r($input['outlet_menu']);exit;
if (isset($input['outlet_menu']) && is_array($input['outlet_menu'])) {
// Filter out empty values (including 0 and '')
$filteredMenuIds = array_filter($input['outlet_menu'], function($menuId) {
return $menuId !== '' && $menuId !== null && $menuId !== 0;
});
if (!empty($filteredMenuIds)) {
// Fetch existing menu items
$existingMenu = $this->outlet_menu
->where('outlet_id', $id)
->where('deleted_at', null)
->findAll();
$existingMenuIds = array_column($existingMenu, 'menu_item_id', 'id');
$updatedMenuIds = [];
foreach ($filteredMenuIds as $menuId) {
if (in_array($menuId, $existingMenuIds)) {
$updatedMenuIds[] = $menuId;
} else {
$newId = $this->outlet_menu->insert([
'outlet_id' => $id,
'menu_item_id' => $menuId,
]);
$updatedMenuIds[] = $newId;
}
}
// Delete unused menu items
foreach ($existingMenu as $existing) {
if (!in_array($existing['menu_item_id'], $updatedMenuIds)) {
$this->outlet_menu
->where('menu_item_id', $existing['menu_item_id'])
->where('outlet_id', $id)
->where('deleted_at', null)
->delete();
}
}
} else {
// Delete ALL menu items if array is empty after filtering
$this->outlet_menu
->where('outlet_id', $id)
->where('deleted_at', null)
->delete();
}
}
// Handle operating hours exceptions
if (isset($input['outlet_operating_hours_exceptions']) && is_array($input['outlet_operating_hours_exceptions'])) {
$existingExceptions = $this->outletOperatingHoursExceptions
->where('outlet_id', $id)
->where('deleted_at', null)
->findAll();
$existingExceptionKeys = [];
foreach ($existingExceptions as $ex) {
$key = $ex['date'].'|'.$ex['start_time'].'|'.$ex['end_time'];
$existingExceptionKeys[$key] = $ex['id'];
}
$updatedExceptionIds = [];
foreach ($input['outlet_operating_hours_exceptions'] as $exception) {
$exceptionData = [
'outlet_id' => $id,
'date' => $exception['date'],
'start_time' => $exception['start_time'],
'end_time' => $exception['end_time'],
'notes' => $exception['notes'] ?? null,
'updated_at' => date('Y-m-d H:i:s')
];
$compositeKey = $exception['date'].'|'.$exception['start_time'].'|'.$exception['end_time'];
if (isset($existingExceptionKeys[$compositeKey])) {
$exceptionData['id'] = $existingExceptionKeys[$compositeKey];
$this->outletOperatingHoursExceptions->save($exceptionData);
$updatedExceptionIds[] = $exceptionData['id'];
} else {
$exceptionData['created_at'] = date('Y-m-d H:i:s');
$newId = $this->outletOperatingHoursExceptions->insert($exceptionData);
$updatedExceptionIds[] = $newId;
}
}
// Soft delete removed exceptions
foreach ($existingExceptions as $existingException) {
if (!in_array($existingException['id'], $updatedExceptionIds)) {
$this->outletOperatingHoursExceptions
->where('id', $existingException['id'])
->set(['deleted_at' => date('Y-m-d H:i:s')])
->update();
}
}
}
// Commit transaction
$this->db->transCommit();
// Prepare response
$result = [
'outlet' => array_merge($outlet_data, ['id' => $id]),
'outlet_tax' => $input['outlet_tax'] ?? [],
'outlet_images' => $images['outlet_images'] ?? [],
'outlet_operating_days' => $input['outlet_operating_days'] ?? [],
'outlet_operating_hours' => $input['outlet_operating_hours'] ?? [],
'outlet_operating_hours_exceptions' => $input['outlet_operating_hours_exceptions'] ?? []
];
return $this->respond(['status' => 200, 'result' => $result]);
} catch (\Exception $e) {
$this->db->transRollback();
return $this->respond(['status' => 400, 'message' => 'Failed to update outlet: ' . $e->getMessage()]);
}
}
public function delete($id = null)
{
$outlet = $this->outlet->find($id);
if(empty($outlet)){
return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
}
$this->outlet->delete($id);
$this->outletTax->where('outlet_id', $id)->delete();
$this->outletOperatingDays->where('outlet_id', $id)->delete();
$this->outletOperatingHours->where('outlet_id', $id)->delete();
$this->outletOperatingHoursExceptions->where('outlet_id', $id)->delete();
return $this->respond(['status' => 200, 'result' => 'Outlet deleted successfully.']);
}
public function updatePassword($id = null)
{
$outlet = $this->outlet->find($id);
if(empty($outlet)){
return $this->respond(['status' => 400, 'result' => 'No outlet data found.']);
}
$password = $this->request->getVar('password');
$this->outlet->update($id, ['password' => md5(md5($password))]);
return $this->respond(['status' => 200, 'result' => 'Outlet password updated successfully.']);
}
public function addBulk()
{
$rules = [
'outlet_ids' => 'required|is_array',
'menu_item_ids' => 'required|is_array',
];
if (!$this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$outletIds = $this->request->getVar('outlet_ids');
$menuItemIds = $this->request->getVar('menu_item_ids');
$insertData = [];
$insertCount = 0;
$restoreCount = 0;
foreach ($outletIds as $outletId) {
foreach ($menuItemIds as $menuItemId) {
$exists = $this->outlet_menu
->withDeleted() // include soft deleted to detect them
->where('outlet_id', $outletId)
->where('menu_item_id', $menuItemId)
->first();
if (!$exists) {
$insertData[] = [
'outlet_id' => $outletId,
'menu_item_id' => $menuItemId,
];
$insertCount++;
} elseif (!empty($exists['deleted_at'])) {
// Restore if it was soft deleted
$this->outlet_menu
->update($exists['id'], ['deleted_at' => null]);
$restoreCount++;
}
}
}
if (!empty($insertData)) {
$this->outlet_menu->insertBatch($insertData);
}
return $this->respond([
'status' => 200,
'message' => "Menu items added to outlets successfully.",
'added' => $insertCount,
'restored' => $restoreCount
]);
}
public function deleteBulk()
{
$rules = [
'outlet_ids' => 'required|is_array',
'menu_item_ids' => 'required|is_array',
];
if (!$this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$outletIds = $this->request->getVar('outlet_ids');
$menuItemIds = $this->request->getVar('menu_item_ids');
$deleteCount = 0;
foreach ($outletIds as $outletId) {
// Soft delete only the specified menu items for each outlet
$deleteCount += $this->outlet_menu
->where('outlet_id', $outletId)
->whereIn('menu_item_id', $menuItemIds)
->delete(); // soft delete because model usesSoftDeletes = true
}
return $this->respond([
'status' => 200,
'message' => "Outlet menus deleted successfully.",
'deleted' => $deleteCount,
'outlets_processed' => count($outletIds),
'menu_items_processed' => count($menuItemIds)
]);
}
}
@@ -0,0 +1,542 @@
<?php
namespace App\Controllers\Backend;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use App\Models\PromoSetting;
use App\Models\PromoCode;
use App\Models\PromoRedemptionRecord;
helper('promo'); // loads app/Helpers/promo_helper.php
class PromoSettingController extends ResourceController
{
private $promoSetting;
private $promoCode;
private $promoRedemptionRecord;
protected $db;
public function __construct()
{
$this->promoSetting = new PromoSetting();
$this->promoCode = new PromoCode();
$this->promoRedemptionRecord = new PromoRedemptionRecord();
$this->db = \Config\Database::connect();
}
public function index()
{
$promoSettingsData = $this->promoSetting->findAll();
// print_r($promoSettingsData);exit;
if(empty($promoSettingsData)){
return $this->respond(['status' => 400, 'result' => 'No data found.']);
}
$result = [];
foreach($promoSettingsData as $key => $value){
$result[$key] = [
"id" => $value['id'],
"title" => $value['title'],
"status" => $value['status'],
];
$promoCode = $this->promoCode->where('promo_setting_id', $value['id'])->findAll()[0];
if(!empty($promoCode)){
$result[$key]['promoCode'] = $promoCode['code'];
$result[$key]['total_redemption_limit'] = $promoCode['total_redemption_limit'];
$result[$key]['start_date'] = $promoCode['start_date'];
$result[$key]['end_date'] = $promoCode['end_date'];
$count_redemptions = $this->promoRedemptionRecord->where('promo_codes_id', $promoCode['id'])->countAllResults();
$result[$key]['left_redemption'] = $promoCode['total_redemption_limit'] - $count_redemptions;
}
}
return $this->respond(['status' => 200, 'message' => 'Retrieve Promo Setting Successfully!', 'result' => $result]);
}
public function show($id = null)
{
$promoSetting = $this->promoSetting->find($id);
if(empty($promoSetting)){
return $this->respond(['status' => 400, 'result' => 'No data found.']);
}
// print_r(json_decode($promoSetting['promo_setting'], true));exit;
$promoSettingData = revertPromoSetting(json_decode($promoSetting['promo_setting'], true));
// print_r($promoSettingData);exit;
$result = [
"id" => $promoSetting['id'],
"promotionType" => $promoSetting['promotion_type'],
"promotionName" => $promoSetting['title'],
"promotionDescription" => $promoSetting['description'],
//promo_setting
"discountAmount" => $promoSettingData['discountAmount'],
"discountType" => $promoSettingData['discountType'],
"getNumber" => $promoSettingData['getNumber'],
"minimumSpend" => $promoSettingData['minimumSpend'],
"itemCategory1" => $promoSettingData['itemCategory1'],
"itemCategoryID1" => $promoSettingData['itemCategoryID1'],
"itemCategory2" => $promoSettingData['itemCategory2'],
"itemCategoryID2" => $promoSettingData['itemCategoryID2'],
"minimumQuantity" => $promoSettingData['minimumQuantity'],
"everyQuantity" => $promoSettingData['everyQuantity'],
// "minimumAmount" => $promoSettingData['minimumAmount'],
"promoType" => $promoSettingData['promoType'],
];
// print_r($result);exit;
$promoCode = $this->promoCode->where('promo_setting_id', $promoSetting['id'])->findAll()[0];
$result['promoCodeId'] = $promoCode['id'];
$result['promotionCode'] = $promoCode['code'];
$result['usageLimit'] = $promoCode['usage_limit_type'];
$result['voucherLimitPerCustomer'] = $promoCode['usage_limit'];
$result['totalRedemptionLimit'] = $promoCode['total_redemption_limit'];
$result['storeStartDate'] = $promoCode['start_date'];
$result['storeEndDate'] = $promoCode['end_date'];
$result['customDayTime'] = json_decode($promoCode['customize_validity'], true);
$result['applyToDeliveryPickup'] = $promoCode['promo_order_type'];
// print_r($result);exit;
$count_redemptions = $this->promoRedemptionRecord->where('promo_codes_id', $promoCode['id'])->countAllResults();
$result['left_redemption'] = $promoCode['total_redemption_limit'] - $count_redemptions;
return $this->respond(['status' => 200, 'message' => 'Retrieve Promo Setting Successfully!', 'result' => $result]);
}
public function create()
{
$validationRules = [
"promotionType" => "required",
"promotionName" => "required",
"promotionDescription" => "permit_empty",
"usageLimit" => "required",
"totalRedemptionLimit" => "required",
"voucherLimitPerCustomer" => "permit_empty",
"startDate" => "permit_empty",
"endDate" => "permit_empty",
"customDayTime" => "permit_empty",
"applyToDeliveryPickup" => "required",
];
$validation = $this->validate($validationRules);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$this->db->transBegin();
try {
$applyToDeliveryPickup = $this->request->getVar("applyToDeliveryPickup");
if (!is_array($applyToDeliveryPickup)) {
throw new \Exception("applyToDeliveryPickup must be an array");
}
$validOptions = ['delivery', 'pickup', 'dinein'];
foreach ($applyToDeliveryPickup as $option) {
if (!in_array($option, $validOptions)) {
throw new \Exception("Invalid option in applyToDeliveryPickup: " . $option);
}
}
if (empty($applyToDeliveryPickup)) {
throw new \Exception("applyToDeliveryPickup cannot be empty");
}
$minimumSpend = $this->request->getVar("minimumSpend");
$minimumQuantity = $this->request->getVar("minimumQuantity");
$everyQuantity = $this->request->getVar("everyQuantity");
$itemCategory1 = $this->request->getVar("itemCategory1");
$itemCategoryID1 = $this->request->getVar("itemCategoryID1");
$discountAmount = $this->request->getVar("discountAmount");
$discountType = $this->request->getVar("discountType");
$getNumber = $this->request->getVar("getNumber");
$itemCategory2 = $this->request->getVar("itemCategory2");
$itemCategoryID2 = $this->request->getVar("itemCategoryID2");
$promoType = $this->request->getVar("promoType");
$promoSetting = [
"MinimumSpend" => [
"type" => 'none',
"filter" => [],
"amount_type" => '',
"amount" => 0
],
"Promo" => [
"promo_type" => $promoType,
"discount_type" => $discountType,
"filter_type" => 'total',
"filter" => [],
"amount" => 0,
"free_item" => []
]
];
if (!empty($minimumSpend) || !empty($minimumQuantity) || !empty($everyQuantity)) {
if (!empty($itemCategory1)) {
$promoSetting["MinimumSpend"]["type"] = $itemCategory1;
$promoSetting["MinimumSpend"]["filter"] = is_array($itemCategoryID1) ? $itemCategoryID1 : [];
} else {
$promoSetting["MinimumSpend"]["type"] = "total";
$promoSetting["MinimumSpend"]["filter"] = [];
}
if (!empty($minimumSpend)) {
$promoSetting["MinimumSpend"]["amount_type"] = "amount";
$promoSetting["MinimumSpend"]["amount"] = floatval($minimumSpend);
} elseif (!empty($minimumQuantity)) {
$promoSetting["MinimumSpend"]["amount_type"] = "quantity";
$promoSetting["MinimumSpend"]["amount"] = intval($minimumQuantity);
} elseif (!empty($everyQuantity)) {
$promoSetting["MinimumSpend"]["amount_type"] = "every_quantity";
$promoSetting["MinimumSpend"]["amount"] = intval($everyQuantity);
}
}
$promoSetting["Promo"]["promo_type"] = $promoType;
if ($promoType === "free_item") {
$promoSetting["Promo"]["discount_type"] = '';
} else {
$promoSetting["Promo"]["discount_type"] = $discountType;
}
if (!empty($itemCategory2)) {
$promoSetting["Promo"]["filter_type"] = $itemCategory2;
} else {
$promoSetting["Promo"]["filter_type"] = "total";
}
if ($promoType === "free_item") {
$promoSetting["Promo"]["free_item"] = is_array($itemCategoryID2) ? $itemCategoryID2 : [];
$promoSetting["Promo"]["filter"] = [];
} else {
$promoSetting["Promo"]["filter"] = is_array($itemCategoryID2) ? $itemCategoryID2 : [];
$promoSetting["Promo"]["free_item"] = [];
}
if (!empty($discountAmount)) {
$promoSetting["Promo"]["amount"] = floatval($discountAmount);
} elseif (!empty($getNumber)) {
$promoSetting["Promo"]["amount"] = intval($getNumber);
}
$promoSettingData = [
"promotion_type" => $this->request->getVar("promotionType"),
"title" => $this->request->getVar("promotionName"),
"description" => $this->request->getVar("promotionDescription"),
"promo_setting" => json_encode($promoSetting)
];
$id = $this->promoSetting->insert($promoSettingData);
if(!$id){
throw new \Exception("Failed to create promotion setting.");
}
$promotionCode = $this->request->getVar("promotionCode");
if(!empty($promotionCode)){
$isExists = $this->promoCode->where('code', $promotionCode)->find();
if(!empty($isExists)){
throw new \Exception("Promotion code already exists.");
}
}
$promoOrderTypeString = implode(',', $applyToDeliveryPickup);
$promoCodeData = [
'promo_setting_id' => $id,
"code" => $promotionCode,
"usage_limit_type" => $this->request->getVar("usageLimit"),
"usage_limit" => $this->request->getVar("voucherLimitPerCustomer"),
"total_redemption_limit" => $this->request->getVar("totalRedemptionLimit"),
"start_date" => $this->request->getVar("storeStartDate"),
"end_date" => $this->request->getVar("storeEndDate"),
"customize_validity" => json_encode($this->request->getVar("customDayTime")),
"promo_order_type" => $promoOrderTypeString
];
$promoCodeId = $this->promoCode->insert($promoCodeData);
if(!$promoCodeId){
throw new \Exception("Failed to create promotion code.");
}
$this->db->transCommit();
return $this->respond([
'status' => 200,
'message' => 'Promotion created successfully.',
'data' => [
'promo_setting_id' => $id,
'promo_code_id' => $promoCodeId,
'promo_order_type' => $promoOrderTypeString
]
]);
} catch (\Exception $e) {
$this->db->transRollback();
log_message('error', 'Promotion creation failed: ' . $e->getMessage());
return $this->failServerError('Failed to create promotion: '. $e->getMessage());
}
}
public function update($id = null)
{
$promoSetting = $this->promoSetting->find($id);
if(empty($promoSetting)){
return $this->respond(['status' => 400, 'result' => 'No promotion setting data found.']);
}
$validationRules = [
"promotionType" => "required",
"promotionName" => "required",
"promotionDescription" => "permit_empty",
"usageLimit" => "required",
"totalRedemptionLimit" => "required",
"voucherLimitPerCustomer" => "permit_empty",
"startDate" => "permit_empty",
"endDate" => "permit_empty",
"customDayTime" => "permit_empty",
"applyToDeliveryPickup" => "required",
];
$validation = $this->validate($validationRules);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$this->db->transBegin();
try {
$applyToDeliveryPickup = $this->request->getVar("applyToDeliveryPickup");
if (!is_array($applyToDeliveryPickup)) {
throw new \Exception("applyToDeliveryPickup must be an array");
}
$validOptions = ['delivery', 'pickup', 'dinein'];
foreach ($applyToDeliveryPickup as $option) {
if (!in_array($option, $validOptions)) {
throw new \Exception("Invalid option in applyToDeliveryPickup: " . $option);
}
}
if (empty($applyToDeliveryPickup)) {
throw new \Exception("applyToDeliveryPickup cannot be empty");
}
$minimumSpend = $this->request->getVar("minimumSpend");
$minimumQuantity = $this->request->getVar("minimumQuantity");
$everyQuantity = $this->request->getVar("everyQuantity");
$itemCategory1 = $this->request->getVar("itemCategory1");
$itemCategoryID1 = $this->request->getVar("itemCategoryID1");
// print_r($itemCategory1);
// print_r($itemCategoryID1);
// exit;
$discountAmount = $this->request->getVar("discountAmount");
$discountType = $this->request->getVar("discountType");
$getNumber = $this->request->getVar("getNumber");
$itemCategory2 = $this->request->getVar("itemCategory2");
$itemCategoryID2 = $this->request->getVar("itemCategoryID2");
$promoType = $this->request->getVar("promoType");
$promoSetting = [
"MinimumSpend" => [
"type" => 'none',
"filter" => [],
"amount_type" => '',
"amount" => 0
],
"Promo" => [
"promo_type" => $promoType,
"discount_type" => $discountType,
"filter_type" => 'total',
"filter" => [],
"amount" => 0,
"free_item" => []
]
];
if (!empty($itemCategory1)) {
$promoSetting["MinimumSpend"]["type"] = $itemCategory1;
$promoSetting["MinimumSpend"]["filter"] = is_array($itemCategoryID1) ? $itemCategoryID1 : [];
} else {
$promoSetting["MinimumSpend"]["type"] = "total";
$promoSetting["MinimumSpend"]["filter"] = [];
}
if (!empty($minimumSpend)) {
$promoSetting["MinimumSpend"]["amount_type"] = "amount";
$promoSetting["MinimumSpend"]["amount"] = floatval($minimumSpend);
} elseif (!empty($minimumQuantity)) {
$promoSetting["MinimumSpend"]["amount_type"] = "quantity";
$promoSetting["MinimumSpend"]["amount"] = intval($minimumQuantity);
} elseif (!empty($everyQuantity)) {
$promoSetting["MinimumSpend"]["amount_type"] = "every_quantity";
$promoSetting["MinimumSpend"]["amount"] = intval($everyQuantity);
}
$promoSetting["Promo"]["promo_type"] = $promoType;
if ($promoType === "free_item") {
$promoSetting["Promo"]["discount_type"] = '';
} else {
$promoSetting["Promo"]["discount_type"] = $discountType;
}
if (!empty($itemCategory2)) {
$promoSetting["Promo"]["filter_type"] = $itemCategory2;
} else {
$promoSetting["Promo"]["filter_type"] = "total";
}
if ($promoType === "free_item") {
$promoSetting["Promo"]["free_item"] = is_array($itemCategoryID2) ? $itemCategoryID2 : [];
$promoSetting["Promo"]["filter"] = [];
} else {
$promoSetting["Promo"]["filter"] = is_array($itemCategoryID2) ? $itemCategoryID2 : [];
$promoSetting["Promo"]["free_item"] = [];
}
if (!empty($discountAmount)) {
$promoSetting["Promo"]["amount"] = floatval($discountAmount);
} elseif (!empty($getNumber)) {
$promoSetting["Promo"]["amount"] = intval($getNumber);
}
$promoSettingData = [
"id" => $id,
"promotion_type" => $this->request->getVar("promotionType"),
"title" => $this->request->getVar("promotionName"),
"description" => $this->request->getVar("promotionDescription"),
"promo_setting" => json_encode($promoSetting)
];
$response = $this->promoSetting->save($promoSettingData);
if (!$response) {
throw new \Exception('Failed to update promotion settings.');
}
$promoCode = $this->promoCode->where('promo_setting_id', $id)->find()[0];
if(!$promoCode){
throw new \Exception("Failed to update promotion code.");
}
$promotionCode = $this->request->getVar("promotionCode");
if(!empty($promotionCode)){
$isExists = $this->promoCode->where('code', $promotionCode)->where('id !=', $promoCode['id'])->find();
if(!empty($isExists)){
throw new \Exception("Promotion code already exists.");
}
}
$promoOrderTypeString = implode(',', $applyToDeliveryPickup);
$promoCodeData = [
'id' => $promoCode['id'],
'promo_setting_id' => $id,
'code' => $promotionCode,
'usage_limit_type' => $this->request->getVar("usageLimit"),
'usage_limit' => $this->request->getVar("voucherLimitPerCustomer"),
'total_redemption_limit' => $this->request->getVar("totalRedemptionLimit"),
'start_date' => $this->request->getVar("storeStartDate"),
'end_date' => $this->request->getVar("storeEndDate"),
'customize_validity' => json_encode($this->request->getVar("customDayTime")),
'promo_order_type' => $promoOrderTypeString
];
$promoCodeResponse = $this->promoCode->save($promoCodeData);
if (!$promoCodeResponse) {
throw new \Exception('Failed to update promotion code.');
}
$this->db->transCommit();
return $this->respond([
'status' => 200,
'message' => 'Promotion updated successfully.',
'data' => [
'promo_setting_id' => $id,
'promo_code_id' => $promoCode['id'],
'promo_order_type' => $promoOrderTypeString
]
]);
} catch (\Exception $e) {
$this->db->transRollback();
log_message('error', 'Promotion update failed: ' . $e->getMessage());
return $this->failServerError('Failed to update promotion: '. $e->getMessage());
}
}
public function delete($id = null)
{
$promoSetting = $this->promoSetting->find($id);
// print_r($promoSetting);exit;
if(empty($promoSetting)){
return $this->respond(['status' => 400, 'result' => 'No promotion setting data found.']);
}
$this->promoSetting->delete($id);
$this->promoCode->where('promo_setting_id', $id)->delete();
return $this->respond(['status' => 200, 'result' => 'Promotion deleted successfully.']);
}
public function promoSettingList(){
$promo_setting_list = $this->promoSetting->findAll();
if(empty($promo_setting_list)){
return $this->fail('No promo setting data found!');
}
$data_list = [];
foreach ($promo_setting_list as $key => $value) {
$data_list[] = [
'id' => $value['id'],
'promotion_type' => $value['promotion_type'],
'title' => $value['title'],
'description'=> $value['description'],
'status' => $value['status'],
'promo_setting' => $value['promo_setting'],
];
}
return $this->respond([
'status'=> 200,
'message' => 'Promo setting record found!',
'data'=> $data_list
]);
}
}
+205
View File
@@ -0,0 +1,205 @@
<?php
namespace App\Controllers\Backend;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\PwpModel;
use CodeIgniter\RESTful\ResourceController;
class PwpController extends ResourceController
{
protected $pwpModel;
public function __construct()
{
$this->pwpModel = new PwpModel();
$this->db = db_connect();
}
public function index()
{
$pwps = $this->pwpModel->findAll();
foreach ($pwps as &$pwp) {
$selectedIds = array_filter(array_map('trim', explode(',', $pwp['selected_item'])));
$pwp['selected_item_details'] = [];
if (!empty($selectedIds)) {
$pwp['selected_item_details'] = $this->db->table('menu_items')
->select('id, title, price, status')
->whereIn('id', $selectedIds)
->where('deleted_at', null)
->orderBy("created_at", "ASC")
->get()
->getResultArray();
}
$pwpIds = array_filter(array_map('trim', explode(',', $pwp['pwp_item_id'])));
$pwp['pwp_item_details'] = [];
if (!empty($pwpIds)) {
$pwp['pwp_item_details'] = $this->db->table('menu_items')
->select('id, title, price, status')
->whereIn('id', $pwpIds)
->where('deleted_at', null)
->orderBy("created_at", "DESC")
->get()
->getResultArray();
}
}
return $this->respond([
'status' => 200,
'data' => $pwps
]);
}
public function create()
{
$json = $this->request->getJSON(true);
if (empty($json['mode']) || empty($json['order_index']) || empty($json['amount']) || empty($json['amount_type'])) {
return $this->failValidationErrors('mode, order_index, amount and amount_type are required');
}
$pwpItems = is_array($json['pwp_item_id']) ? implode(',', $json['pwp_item_id']) : $json['pwp_item_id'];
$selectedIds = is_array($json['selected_item']) ? $json['selected_item'] : explode(',', $json['selected_item']);
$selectedItems = implode(',', $selectedIds);
$data = [
'mode' => $json['mode'],
'order_index' => $json['order_index'],
'pwp_item_id' => $pwpItems,
'amount' => $json['amount'],
'amount_type' => $json['amount_type'],
'selected_item' => $selectedItems,
];
if (!$this->pwpModel->insert($data)) {
return $this->fail($this->pwpModel->errors());
}
$pwpItemDetails = [];
if (!empty($pwpItems)) {
$pwpItemArray = explode(',', $pwpItems);
$pwpItemDetails = $this->db->table('menu_items')
->select('id, title, price')
->whereIn('id', $pwpItemArray)
->where('status', 'active')
->get()
->getResultArray();
}
$selectedItemDetails = [];
if (!empty($selectedIds)) {
$selectedItemDetails = $this->db->table('menu_items')
->select('id, title, price')
->whereIn('id', $selectedIds)
->where('status', 'active')
->get()
->getResultArray();
}
return $this->respondCreated([
'message' => 'PWP promo created successfully',
'data' => array_merge($data, [
'pwp_item_id' => $pwpItems,
'pwp_item_details' => $pwpItemDetails,
'selected_item' => $selectedIds,
'selected_item_details' => $selectedItemDetails
])
]);
}
public function show($id = null)
{
$pwp = $this->pwpModel->find($id);
if (!$pwp) {
return $this->failNotFound('PWP not found');
}
$selectedIds = explode(',', $pwp['selected_item']);
$pwp['selected_item_details'] = [];
if (!empty($selectedIds[0])) {
$pwp['selected_item_details'] = $this->db->table('menu_items')
->select('id, title, price, status')
->whereIn('id', $selectedIds)
->where('status', 'active')
->get()
->getResultArray();
}
return $this->respond($pwp);
}
public function update($id = null)
{
$json = $this->request->getJSON(true);
if (empty($json['mode']) || empty($json['order_index']) ) {
return $this->failValidationErrors('mode, order_index are required');
}
$pwpItems = is_array($json['pwp_item_id']) ? implode(',', $json['pwp_item_id']) : $json['pwp_item_id'];
$selectedIds = is_array($json['selected_item']) ? $json['selected_item'] : explode(',', $json['selected_item']);
$selectedItems = implode(',', $selectedIds);
$data = [
'mode' => $json['mode'],
'order_index' => $json['order_index'],
'pwp_item_id' => $pwpItems,
'amount' => $json['amount'] ?? 0.00,
'amount_type' => $json['amount_type'] ?? 'amount',
'selected_item' => $selectedItems,
];
if (!$this->pwpModel->update($id, $data)) {
return $this->fail($this->pwpModel->errors());
}
$selectedItemDetails = [];
if (!empty($selectedIds)) {
$selectedItemDetails = $this->db->table('menu_items')
->select('id, title, price')
->whereIn('id', $selectedIds)
->where('status', 'active')
->get()
->getResultArray();
}
return $this->respond([
'status' => 200,
'message' => 'PWP promo updated successfully',
'data' => array_merge($data, [
'selected_item' => $selectedIds,
'selected_item_details' => $selectedItemDetails
])
]);
}
public function delete($id = null)
{
if (!$this->pwpModel->find($id)) {
return $this->respond([
'status' => 404,
'message' => 'PWP not found'
], 404);
}
if (!$this->pwpModel->delete($id)) {
return $this->respond([
'status' => 500,
'message' => 'Failed to delete PWP'
], 500);
}
return $this->respond([
'status' => 200,
'message' => 'PWP promo deleted successfully'
], 200);
}
}
@@ -0,0 +1,879 @@
<?php
namespace App\Controllers\Backend;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use App\Models\SettingCustomerType;
use App\Models\SettingMembershipTier;
use App\Models\SettingTax;
use App\Models\SlideshowModel;
helper('image');
use App\Models\SettingCheckinRule;
class SettingController extends ResourceController
{
private $customerTypeModel;
private $membershipTierModel;
private $checkinRuleModel;
private $taxModel;
private $slideshowModel;
public function __construct()
{
$this->customerTypeModel = new SettingCustomerType();
$this->membershipTierModel = new SettingMembershipTier();
$this->taxModel = new SettingTax();
$this->checkinRuleModel = new SettingCheckinRule();
$this->slideshowModel = new SlideshowModel();
}
public function customerTypesindex()
{
$types = $this->customerTypeModel->findAll();
if (empty($types)) {
$response = [
'status' => 'success',
'message' => 'No customer type data found.',
'data' => []
];
return $this->respond($response, 200);
}
$response = [
'status' => 'success',
'message' => 'Customer types retrieved successfully.',
'data' => $types
];
return $this->respond($response, 200);
}
public function customerTypesshow($id = null)
{
$type = $this->customerTypeModel->find($id);
if (!$type) {
$response = [
'status' => 'error',
'message' => 'Customer type not found.',
'data' => null
];
return $this->respond($response, 404);
}
$response = [
'status' => 'success',
'message' => 'Customer type retrieved successfully.',
'data' => $type
];
return $this->respond($response, 200);
}
public function customerTypescreate()
{
$validationRules = [
'name' => 'required',
];
if (!$this->validate($validationRules)) {
$response = [
'status' => 'error',
'message' => 'Validation failed.',
'data' => $this->validator->getErrors()
];
return $this->respond($response, 422);
}
$data = [
'name' => $this->request->getVar('name'),
];
$id = $this->customerTypeModel->insert($data);
if ($id) {
$result = $this->customerTypeModel->find($id);
$response = [
'status' => 'success',
'message' => 'Customer type created successfully.',
'data' => $result
];
return $this->respond($response, 201);
}
$response = [
'status' => 'error',
'message' => 'Failed to create customer type.',
'data' => null
];
return $this->respond($response, 500);
}
public function customerTypesupdate($id = null)
{
// Check if customer type exists and is not soft-deleted
$existingType = $this->customerTypeModel->find($id);
if (!$existingType) {
$response = [
'status' => 'error',
'message' => 'Customer type not found.',
'data' => null
];
return $this->respond($response, 404);
}
// Use raw input for PUT/PATCH, or getVar for POST fallback
$input = $this->request->getRawInput();
if (empty($input)) {
$input = $this->request->getVar();
}
$data = [];
if (isset($input['name'])) {
$data['name'] = $input['name'];
}
if (empty($data)) {
$response = [
'status' => 'error',
'message' => 'No data provided to update.',
'data' => null
];
return $this->respond($response, 400);
}
$this->customerTypeModel->update($id, $data);
$updatedType = $this->customerTypeModel->find($id);
$response = [
'status' => 'success',
'message' => 'Customer type updated successfully.',
'data' => $updatedType
];
return $this->respond($response, 200);
}
public function customerTypesdelete($id = null)
{
$existingType = $this->customerTypeModel->find($id);
if (!$existingType) {
$response = [
'status' => 'error',
'message' => 'Customer type not found.',
'data' => null
];
return $this->respond($response, 404);
}
$this->customerTypeModel->delete($id); // This performs soft delete
$response = [
'status' => 'success',
'message' => 'Customer type deleted successfully.',
'data' => null
];
return $this->respond($response, 200);
}
public function membershipTiersIndex()
{
$tiers = $this->membershipTierModel->findAll();
if (empty($tiers)) {
$response = [
'status' => 'error',
'message' => 'No membership tiers found.',
'data' => []
];
return $this->respond($response, 200);
}
$response = [
'status' => 'success',
'message' => 'Membership tiers retrieved successfully.',
'data' => $tiers
];
return $this->respond($response, 200);
}
public function membershipTiersShow($id = null)
{
$tier = $this->membershipTierModel->find($id);
if (!$tier) {
$response = [
'status' => 'error',
'message' => 'Membership tier not found.',
'data' => null
];
return $this->respond($response, 404);
}
$response = [
'status' => 'success',
'message' => 'Membership tier retrieved successfully.',
'data' => $tier
];
return $this->respond($response, 200);
}
public function membershipTiersCreate()
{
$validationRules = [
'name' => 'required',
'min_points' => 'required|numeric',
// 'discount_rate' => 'required|numeric',
// 'category_id' => 'required|integer'
];
if (!$this->validate($validationRules)) {
$response = [
'status' => 'error',
'message' => 'Validation failed.',
'data' => $this->validator->getErrors()
];
return $this->respond($response, 422);
}
$name = $this->request->getVar('name');
$existingTier = $this->membershipTierModel->where('name', $name)->first();
if ($existingTier) {
$response = [
'status' => 'error',
'message' => "A membership tier with the name '{$name}' already exists.",
'data' => null
];
return $this->respond($response, 409); // Conflict
}
$data = [
'name' => $this->request->getVar('name'),
'min_points' => $this->request->getVar('min_points'),
'discount_rate' => $this->request->getVar('discount_rate'),
'color' => $this->request->getVar('color'),
'category_id' => $this->request->getVar('category_id'), // Add category_id
];
$id = $this->membershipTierModel->insert($data);
if ($id) {
$result = $this->membershipTierModel->find($id);
$response = [
'status' => 'success',
'message' => 'Membership tier created successfully.',
'data' => $result
];
return $this->respond($response, 201);
}
$response = [
'status' => 'error',
'message' => 'Failed to create membership tier.',
'data' => null
];
return $this->respond($response, 500);
}
public function membershipTiersUpdate($id = null)
{
$existing = $this->membershipTierModel->find($id);
if (!$existing) {
$response = [
'status' => 'error',
'message' => 'Membership tier not found.',
'data' => null
];
return $this->respond($response, 404);
}
$input = $this->request->getRawInput();
if (empty($input)) {
$input = $this->request->getVar();
}
$data = [];
if (isset($input['name'])) {
$data['name'] = $input['name'];
}
if (isset($input['min_points'])) {
$data['min_points'] = $input['min_points'];
}
// if (isset($input['discount_rate'])) {
// $data['discount_rate'] = $input['discount_rate'];
// }
if (isset($input['color'])) {
$data['color'] = $input['color'];
}
// if (isset($input['category_id'])) {
// $data['category_id'] = $input['category_id']; // Add category_id
// }
if (empty($data)) {
$response = [
'status' => 'error',
'message' => 'No data provided to update.',
'data' => null
];
return $this->respond($response, 400);
}
$this->membershipTierModel->update($id, $data);
$updated = $this->membershipTierModel->find($id);
$response = [
'status' => 'success',
'message' => 'Membership tier updated successfully.',
'data' => $updated
];
return $this->respond($response, 200);
}
public function membershipTiersDelete($id = null)
{
$existing = $this->membershipTierModel->find($id);
if (!$existing) {
$response = [
'status' => 'error',
'message' => 'Membership tier not found.',
'data' => null
];
return $this->respond($response, 404);
}
$this->membershipTierModel->delete($id);
$response = [
'status' => 'success',
'message' => 'Membership tier deleted successfully.',
'data' => null
];
return $this->respond($response, 200);
}
public function taxIndex()
{
$taxes = $this->taxModel->findAll();
if (empty($taxes)) {
$response = [
'status' => 'error',
'message' => 'No tax data found.',
'data' => []
];
return $this->respond($response, 200);
}
$response = [
'status' => 'success',
'message' => 'Tax data retrieved successfully.',
'data' => $taxes
];
return $this->respond($response, 200);
}
public function taxShow($id = null)
{
$tax = $this->taxModel->find($id);
if (!$tax) {
$response = [
'status' => 'error',
'message' => 'Tax entry not found.',
'data' => null
];
return $this->respond($response, 404);
}
$response = [
'status' => 'success',
'message' => 'Tax entry retrieved successfully.',
'data' => $tax
];
return $this->respond($response, 200);
}
public function taxCreate()
{
$validationRules = [
'outlet_id' => 'required',
'tax_type' => 'required',
'tax_rate' => 'required|numeric',
'order_type' => 'required',
];
if (!$this->validate($validationRules)) {
$response = [
'status' => 'error',
'message' => 'Validation failed.',
'data' => $this->validator->getErrors()
];
return $this->respond($response, 400);
}
// Process outlet_ids - convert to comma-separated string
$outletIds = $this->request->getPost('outlet_id');
// If it's an array (from multiple select), convert to comma-separated string
if (is_array($outletIds)) {
$outletIds = implode(',', $outletIds);
}
// Validate that outlet_ids contain only integers and commas
if (!preg_match('/^[0-9,]+$/', $outletIds)) {
$response = [
'status' => 'error',
'message' => 'Invalid outlet IDs format. Only integers and commas allowed.',
'data' => null
];
return $this->respond($response, 400);
}
$data = [
'outlet_id' => $outletIds,
'tax_type' => $this->request->getPost('tax_type'),
'tax_rate' => $this->request->getPost('tax_rate'),
'order_type' => $this->request->getVar('order_type'),
];
$id = $this->taxModel->insert($data);
if ($id) {
$result = $this->taxModel->find($id);
$response = [
'status' => 'success',
'message' => 'Tax created successfully.',
'data' => $result
];
return $this->respond($response, 201);
}
$response = [
'status' => 'error',
'message' => 'Failed to create tax entry.',
'data' => null
];
return $this->respond($response, 500);
}
public function taxUpdate($id = null)
{
$tax = $this->taxModel->find($id);
if (!$tax) {
$response = [
'status' => 'error',
'message' => 'Tax entry not found.',
'data' => null
];
return $this->respond($response, 404);
}
$data = [];
// Process outlet_ids if provided
if ($this->request->getPost('outlet_id')) {
$outletIds = $this->request->getPost('outlet_id');
// If it's an array, convert to comma-separated string
if (is_array($outletIds)) {
$outletIds = implode(',', $outletIds);
}
// Validate that outlet_ids contain only integers and commas
if (!preg_match('/^[0-9,]+$/', $outletIds)) {
$response = [
'status' => 'error',
'message' => 'Invalid outlet IDs format. Only integers and commas allowed.',
'data' => null
];
return $this->respond($response, 400);
}
$data['outlet_id'] = $outletIds;
}
// Add other fields if provided
if ($this->request->getPost('tax_type')) {
$data['tax_type'] = $this->request->getPost('tax_type');
}
if ($this->request->getPost('tax_rate')) {
$data['tax_rate'] = $this->request->getPost('tax_rate');
}
if ($this->request->getVar('order_type')) {
$data['order_type'] = $this->request->getVar('order_type');
}
if (empty($data)) {
$response = [
'status' => 'error',
'message' => 'No data provided to update.',
'data' => null
];
return $this->respond($response, 400);
}
$this->taxModel->update($id, $data);
$updated = $this->taxModel->find($id);
$response = [
'status' => 'success',
'message' => 'Tax updated successfully.',
'data' => $updated
];
return $this->respond($response, 200);
}
public function taxDelete($id = null)
{
$tax = $this->taxModel->find($id);
if (!$tax) {
$response = [
'status' => 'error',
'message' => 'Tax entry not found.',
'data' => null
];
return $this->respond($response, 404);
}
$this->taxModel->delete($id);
$response = [
'status' => 'success',
'message' => 'Tax deleted successfully.',
'data' => null
];
return $this->respond($response, 200);
}
// public function slideshowIndex()
// {
// $slides = $this->slideshowModel->findAll();
// return $this->respond(['status' => 200, 'result' => $slides]);
// }
public function slideshowIndex()
{
$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 = $this->slideshowModel->orderBy($orderBy, $sort);
if ($this->slideshowModel->useSoftDeletes) {
$builder = $builder->where('deleted_at', null);
}
if ($limit > 0) {
$offset = ($page - 1) * $limit;
$slides = $builder->findAll($limit, $offset);
$total = $this->slideshowModel->where('deleted_at', null)->countAllResults();
} else {
$slides = $builder->findAll();
$total = count($slides);
}
return $this->respond([
'status' => 200,
'result' => $slides,
'pagination' => [
'page' => $page,
'limit' => $limit,
'total' => $total
]
]);
}
// SHOW a single slide by id
public function slideshowShow($id = null)
{
$slide = $this->slideshowModel->find($id);
if (!$slide) {
return $this->failNotFound('Slideshow not found.');
}
return $this->respond(['status' => 200, 'result' => $slide]);
}
// CREATE a new slide
public function slideshowCreate()
{
$slideImage = $this->request->getFile('url');
$imageUrl = null;
$compressedImageUrl = null;
if ($slideImage && $slideImage->isValid() && !$slideImage->hasMoved()) {
$result = save_image_with_compression(
$slideImage,
FCPATH . 'backend/uploads/slideshow',
FCPATH . 'backend/uploads/slideshow_compressed',
900, // width of compressed version
80 // quality (0-100)
);
$imageUrl = base_url('backend/uploads/slideshow/' . basename($result['original']));
$compressedImageUrl = base_url('backend/uploads/slideshow_compressed/' . basename($result['compressed']));
}
$data = [
'type' => $this->request->getVar('type'),
'title' => $this->request->getVar('title'),
'description' => $this->request->getVar('description'),
'order' => $this->request->getVar('order'),
'status' => $this->request->getVar('status'),
'url' => $imageUrl,
'compressed_url' => $compressedImageUrl,
];
$id = $this->slideshowModel->insert($data);
if ($id) {
$result = $this->slideshowModel->find($id);
return $this->respond(['status' => 200, 'message' => 'Slideshow created.', 'result' => $result]);
}
return $this->fail('Failed to create slideshow entry.');
}
// UPDATE an existing slide
public function slideshowUpdate($id = null)
{
$slide = $this->slideshowModel->find($id);
if (!$slide) {
return $this->failNotFound('Slideshow not found.');
}
$input = $this->request->getVar();
$file = $this->request->getFile('url');
if ($file && $file->isValid() && !$file->hasMoved()) {
$result = save_image_with_compression(
$file,
FCPATH . 'backend/uploads/slideshow',
FCPATH . 'backend/uploads/slideshow_compressed',
900, // width of compressed version
80 // quality
);
$input['url'] = base_url('backend/uploads/slideshow/' . basename($result['original']));
$input['compressed_url'] = base_url('backend/uploads/slideshow_compressed/' . basename($result['compressed']));
} else if ($this->request->getVar('url')) {
$input['url'] = $this->request->getVar('url');
}
// print_r($data);exit;
$data = array_filter([
'type' => $input['type'] ?? null,
'url' => $input['url'] ?? null,
'compressed_url' => $input['compressed_url'] ?? null,
'title' => $input['title'] ?? null,
'description' => $input['description'] ?? null,
'order' => $input['order'] ?? null,
'status' => $input['status'] ?? null,
], function ($value) {
return $value !== null;
});
// print_r($data);exit;
if (empty($data)) {
return $this->fail('No data provided to update.');
}
$this->slideshowModel->update($id, $data);
$updated = $this->slideshowModel->find($id);
return $this->respond(['status' => 200, 'message' => 'Slideshow updated.', 'result' => $updated]);
}
// DELETE a slide
public function slideshowDelete($id = null)
{
$slide = $this->slideshowModel->find($id);
if (!$slide) {
return $this->failNotFound('Slideshow entry not found.');
}
$this->slideshowModel->delete($id);
return $this->respond(['status' => 200, 'message' => 'Slideshow deleted Successfully.']);
}
public function createCheckinRule()
{
$checkinCount = $this->request->getVar('checkin_count');
$rewardPoint = $this->request->getVar('reward_point');
if ($checkinCount === null || $rewardPoint === null) {
$response = [
'status' => 'error',
'message' => 'Check-in count and Reward point are required.',
'data' => null
];
return $this->respond($response, 400);
}
// Ensure both are positive numbers
if (!is_numeric($checkinCount) || $checkinCount <= 0 || !is_numeric($rewardPoint) || $rewardPoint <= 0) {
$response = [
'status' => 'error',
'message' => 'Both Check-in count and reward point must be positive numbers.',
'data' => null
];
return $this->respond($response, 400);
}
// Check for duplicate checkin_count
$existing = $this->checkinRuleModel->where('checkin_count', (int)$checkinCount)->first();
if ($existing) {
return $this->respond([
'status' => 'error',
'message' => 'A rule with the same check-in count already exists.',
'data' => null
], 409);
}
$data = [
'checkin_count' => (int) $checkinCount,
'reward_point' => number_format((float) $rewardPoint, 2, '.', '')
];
$this->checkinRuleModel->insert($data);
$response = [
'status' => 'success',
'message' => 'Check-in rule created successfully.',
'data' => $data
];
return $this->respond($response, 201);
}
public function getCheckinRules()
{
$rules = $this->checkinRuleModel
->orderBy('checkin_count', 'DESC')
->findAll();
$response = [
'status' => 'success',
'message' => 'Check-in rules retrieved successfully.',
'data' => $rules
];
return $this->respond($response, 200);
}
public function updateCheckinRule($id)
{
$checkinCount = $this->request->getVar('checkin_count');
$rewardPoint = $this->request->getVar('reward_point');
// Check if rule exists
$rule = $this->checkinRuleModel->find($id);
if (!$rule) {
$response = [
'status' => 'error',
'message' => 'Check-in rule not found.',
'data' => null
];
return $this->respond($response, 404);
}
// Validate input
if ($checkinCount === null || $rewardPoint === null) {
$response = [
'status' => 'error',
'message' => 'checkin_count and reward_point are required.',
'data' => null
];
return $this->respond($response, 400);
}
if (!is_numeric($checkinCount) || $checkinCount <= 0 || !is_numeric($rewardPoint) || $rewardPoint <= 0) {
$response = [
'status' => 'error',
'message' => 'Both checkin_count and reward_point must be positive numbers.',
'data' => null
];
return $this->respond($response, 400);
}
$existing = $this->checkinRuleModel
->where('checkin_count', (int)$checkinCount)
->where('id !=', $id)
->first();
if ($existing) {
return $this->respond([
'status' => 'error',
'message' => 'Another rule with the same check-in count already exists.',
'data' => null
], 409);
}
$data = [
'checkin_count' => (int) $checkinCount,
'reward_point' => (float) $rewardPoint,
];
$this->checkinRuleModel->update($id, $data);
$response = [
'status' => 'success',
'message' => 'Check-in rule updated successfully.',
'data' => $data
];
return $this->respond($response, 200);
}
public function deleteCheckinRule($id)
{
// Check if the rule exists
$rule = $this->checkinRuleModel->find($id);
if (!$rule) {
$response = [
'status' => 'error',
'message' => 'Check-in rule not found.',
'data' => null
];
return $this->respond($response, 404);
}
// Delete the rule
$this->checkinRuleModel->delete($id);
$response = [
'status' => 'success',
'message' => 'Check-in rule deleted successfully.',
'data' => ['id' => $id]
];
return $this->respond($response, 200);
}
}
@@ -0,0 +1,147 @@
<?php
namespace App\Controllers\Backend;
use CodeIgniter\RESTful\ResourceController;
use App\Models\StoreDiscount;
class StoreDiscountController extends ResourceController
{
public function index()
{
$storeDiscountModel = new StoreDiscount();
$data = $storeDiscountModel->findAll();
return $this->respond([
'status' => 'success',
'message' => 'Store discounts fetched successfully',
'data' => $data
], 200);
}
public function show($id = null)
{
$storeDiscountModel = new StoreDiscount();
$data = $storeDiscountModel->find($id);
return $this->respond([
'status' => 'success',
'message' => 'Store discount fetched successfully',
'data' => $data
], 200);
}
public function create()
{
$rules = [
'discount_name' => 'required|string',
'discount_type' => 'required|string',
'discount_value' => 'required|numeric',
'outlet_list' => 'required|is_array',
'menu_item_list' => 'required|is_array',
'status' => 'required|string',
];
if (!$this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$storeDiscountModel = new StoreDiscount();
// Insert data to database outlet_list is array and store it in JSON
$discount_name = $this->request->getVar('discount_name');
$discount_type = $this->request->getVar('discount_type');
$discount_value = $this->request->getVar('discount_value');
$outlet_list = $this->request->getVar('outlet_list');
$menu_item_list = $this->request->getVar('menu_item_list');
$status = $this->request->getVar('status');
$implode_outlet_list = implode(',', $outlet_list);
$implode_menu_item_list = implode(',', $menu_item_list);
$data = [
'discount_name' => $discount_name,
'discount_type' => $discount_type,
'discount_value' => $discount_value,
'outlet_list' => $implode_outlet_list,
'menu_item_list' => $implode_menu_item_list,
'status' => $status,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
];
$storeDiscountModel->insert($data);
return $this->respond([
'status' => 'success',
'message' => 'Store discount created successfully',
'data' => $data
], 200);
}
public function update($id = null)
{
$storeDiscountModel = new StoreDiscount();
$storeDiscount = $storeDiscountModel->find($id);
if(!$storeDiscount) {
return $this->respond([
'status' => 'error',
'message' => 'Store discount not found',
'data' => null
], 404);
}
$rules = [
'discount_name' => 'required|string',
'discount_type' => 'required|string',
'discount_value' => 'required|numeric',
'outlet_list' => 'required|is_array',
'menu_item_list' => 'required|is_array',
'status' => 'required|string',
];
if (!$this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$discount_name = $this->request->getVar('discount_name');
$discount_type = $this->request->getVar('discount_type');
$discount_value = $this->request->getVar('discount_value');
$outlet_list = $this->request->getVar('outlet_list');
$menu_item_list = $this->request->getVar('menu_item_list');
$status = $this->request->getVar('status');
$implode_outlet_list = implode(',', $outlet_list);
$implode_menu_item_list = implode(',', $menu_item_list);
$data = [
'discount_name' => $discount_name,
'discount_type' => $discount_type,
'discount_value' => $discount_value,
'outlet_list' => $implode_outlet_list,
'menu_item_list' => $implode_menu_item_list,
'status' => $status,
'updated_at' => date('Y-m-d H:i:s'),
];
$storeDiscountModel->update($id, $data);
return $this->respond([
'status' => 'success',
'message' => 'Store discount updated successfully',
'data' => $data
], 200);
}
public function delete($id = null){
$storeDiscountModel = new StoreDiscount();
$storeDiscount = $storeDiscountModel->find($id);
if(!$storeDiscount) {
return $this->respond([
'status' => 'error',
'message' => 'Store discount not found',
'data' => null
], 404);
}
$storeDiscountModel->delete($id);
return $this->respond([
'status' => 'success',
'message' => 'Store discount deleted successfully',
'data' => null
], 200);
}
}
+167
View File
@@ -0,0 +1,167 @@
<?php
namespace App\Controllers\Backend;
use App\Models\Tags;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
class TagController extends ResourceController
{
private $tags;
public function __construct()
{
$this->tags = new Tags();
}
public function index()
{
$tags = $this->tags->findAll();
if (empty($tags)) {
return $this->fail("No tags found.", 400);
}
$tagData = [];
foreach ($tags as $tag) {
$tagData[] = [
'id' => $tag['id'],
'title' => $tag['title'],
'icon_url' => getImagePath('tags', $tag['icon_url']),
'created_at' => $tag['created_at'],
];
}
return $this->respond([
'status' => 200,
'message' => 'Tags found.',
'data' => $tagData
]);
}
public function show($id = null)
{
$tag = $this->tags->find($id);
if (empty($tag)) {
return $this->fail("Tag not found.", 400);
}
$tag['icon_url'] = getImagePath('tags', $tag['icon_url']);
unset($tag['updated_at']);
unset($tag['deleted_at']);
return $this->respond([
'status' => 200,
'message' => 'Tag found.',
'data' => $tag
]);
}
public function create()
{
$validation = $this->validate([
'title' => 'required',
'icon' => 'permit_empty|is_image[icon]',
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$title = $this->request->getVar('title');
$icon = $this->request->getFile('icon');
$iconPath = '';
$tag = ['title' => $title];
$id = $this->tags->insert($tag);
if (!$id) {
return $this->fail('Failed to create tag.', 400);
}
if ($icon && $icon->isValid() && !$icon->hasMoved()) {
$uploadPath = $_SERVER['DOCUMENT_ROOT'] . '/backend/uploads/tags/';
if (!is_dir($uploadPath)) {
mkdir($uploadPath, 0755, true);
}
$newIconName = $id . '_' . time() . '.png';
$icon->move($uploadPath, $newIconName);
$iconPath = $newIconName;
$this->tags->update($id, ['icon_url' => $iconPath]);
}
return $this->respond([
'status' => 200,
'message' => 'Tag successfully created!'
]);
}
public function update($id = null)
{
$tag = $this->tags->find($id);
if (empty($tag)) {
return $this->fail("Tag not found.", 400);
}
$validation = $this->validate([
'title' => 'required',
'icon' => 'permit_empty|is_image[icon]',
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$title = $this->request->getVar('title');
$icon = $this->request->getFile('icon');
$updatedData = ['title' => $title];
$iconPath = $tag['icon_url'];
if ($icon && $icon->isValid() && !$icon->hasMoved()) {
$uploadPath = $_SERVER['DOCUMENT_ROOT'] . '/backend/uploads/tags/';
if (!is_dir($uploadPath)) {
mkdir($uploadPath, 0755, true);
}
$newIconName = $id . '_' . time() . '.png';
$icon->move($uploadPath, $newIconName);
$iconPath = $newIconName;
}
$updatedData['icon_url'] = $iconPath;
$this->tags->update($id, $updatedData);
return $this->respond([
'status' => 200,
'message' => 'Tag successfully updated!'
]);
}
public function delete($id = null)
{
$tag = $this->tags->find($id);
if (empty($tag)) {
return $this->fail('Tag not found.', 400);
}
$this->tags->delete($id);
return $this->respond([
'status' => 200,
'message' => 'Tag successfully deleted!'
]);
}
}
+173
View File
@@ -0,0 +1,173 @@
<?php
namespace App\Controllers\Backend;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\TopupModel;
use CodeIgniter\HTTP\ResponseTrait;
use CodeIgniter\RESTful\ResourceController;
class TopupController extends ResourceController
{
use ResponseTrait;
private $topups;
public function __construct()
{
$this->topups = new TopupModel();
}
public function index()
{
// echo(123);exit;
$data = $this->topups
->select('topup.*, customers.customer_wallet, customers.phone, customers.name')
->join('customers', 'customers.id = topup.customer_id', 'left')
->orderBy('topup.created_at', 'DESC')
->findAll();
return $this->respond([
'status' => 200,
'data' => $data,
]);
}
public function create()
{
// echo('123'); exit;
$payload = $this->request->getJSON(true) ?? $this->request->getPost();
$rules = [
'customer_id' => 'required|integer',
'amount' => 'required|decimal|greater_than[0]',
'payment_method' => 'required|string|max_length[50]',
'topup_setting_id' => 'permit_empty|integer',
'credit' => 'permit_empty|decimal',
'other_amount' => 'permit_empty|decimal',
'status' => 'permit_empty|in_list[pending,completed,failed]'
];
// echo(123);
if (!$this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$topupNumber = 'Test-123123';
$data = [
'topup_setting_id' => $payload['topup_setting_id'] ?? null,
'customer_id' => $payload['customer_id'],
'topup_number' => $topupNumber,
'amount' => $payload['amount'],
'credit' => $payload['credit'],
'payment_method' => $payload['payment_method'],
'other_amount' => $payload['other_amount'] ?? null,
'status' => $payload['status']
];
$id = $this->topups->insert($data, true);
if (!$id) {
return $this->fail('Topup creation failed', 400);
}
return $this->respond([
'status' => 201,
'message' => 'Topup created successfully',
'data' => $this->topups->find($id)
]);
}
public function update($id = null)
{
$id = (int) $id;
if (!$this->topups->find($id)) {
return $this->fail('Topup not found', 404);
}
$payload = $this->request->getJSON(true) ?? $this->request->getPost();
$rules = [
'status' => 'permit_empty|in_list[pending,completed,failed]',
'amount' => 'permit_empty|decimal|greater_than[0]',
'credit' => 'permit_empty|decimal',
'payment_method' => 'permit_empty|string|max_length[50]'
];
if (!$this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
if (!$this->topups->update($id, $payload)) {
return $this->fail('Update failed', 400);
}
return $this->respond([
'status' => 200,
'message' => 'Topup updated successfully',
'data' => $this->topups->find($id)
]);
}
public function delete($id = null)
{
$id = (int) $id;
if (!$this->topups->find($id)) {
return $this->fail('Topup not found', 404);
}
if (!$this->topups->delete($id)) {
return $this->fail('Delete failed', 400);
}
return $this->respond([
'status' => 200,
'message' => 'Topup deleted successfully'
]);
}
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,112 @@
<?php
namespace App\Controllers\Backend;
use App\Controllers\BaseController;
use App\Models\TopupSettingModel;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\RESTful\ResourceController;
class TopupSettingController extends ResourceController
{
use ResponseTrait;
private $settings;
public function __construct()
{
$this->settings = new TopupSettingModel();
}
public function index()
{
$data = $this->settings
->orderBy('created_at', 'DESC')
->findAll();
return $this->respond([
'status' => 200,
'data' => $data,
]);
}
public function create()
{
// echo(123123);exit;
$payload = $this->request->getJSON(true) ?? $this->request->getPost();
$rules = [
'topup_amount' => 'required|decimal|greater_than[0]',
'credit_amount' => 'required|decimal|greater_than_equal_to[0]',
'status' => 'required|in_list[active,inactive]',
];
if (! $this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$id = $this->settings->insert([
'topup_amount' => $payload['topup_amount'],
'credit_amount' => $payload['credit_amount'],
'status' => $payload['status'],
], true);
if (! $id) {
return $this->fail('Create failed', 400);
}
return $this->respond([
'status' => 200,
'message' => 'Topup Setting Created',
'data' => $this->settings->find($id),
]);
}
public function update($id = null)
{
// echo(123);exit;
$id = (int) $id;
if (! $this->settings->find($id)) {
return $this->fail('Not found', 404);
}
$payload = $this->request->getJSON(true) ?? $this->request->getRawInput();
$rules = [
'topup_amount' => 'permit_empty|decimal|greater_than[0]',
'credit_amount' => 'permit_empty|decimal|greater_than_equal_to[0]',
'status' => 'permit_empty|in_list[active,inactive]',
];
if (! $this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
if (! $this->settings->update($id, $payload)) {
return $this->fail('Update failed', 400);
}
return $this->respond([
'status' => 200,
'message' => 'Topup Setting Updated',
'data' => $this->settings->find($id),
]);
}
public function delete($id = null)
{
$id = (int) $id;
if (! $this->settings->find($id)) {
return $this->fail('Not found', 404);
}
if (! $this->settings->delete($id)) {
return $this->fail('Delete failed', 400);
}
return $this->respond([
'status' => 200,
'message' => 'Topup Setting deleted',
]);
}
}
+327
View File
@@ -0,0 +1,327 @@
<?php
namespace App\Controllers\Backend;
use App\Controllers\BaseController;
use App\Models\User;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Outlet;
use CodeIgniter\RESTful\ResourceController;
class UserController extends ResourceController
{
private $user;
private $outletModel;
public function __construct()
{
$this->user = new User();
$this->outletModel = new Outlet();
}
public function index()
{
$user_id = $this->request->getVar('user_id');
// Get the requesting user's data to check their role
$requesting_user = $this->user->find($user_id);
if (!$requesting_user) {
$response = [
'status' => 'error',
'message' => 'Requesting user not found.',
'data' => null
];
return $this->respond($response, 404);
}
// If user is admin, get all users
if ($requesting_user['role'] === 'admin') {
$users = $this->user->findAll();
} else {
// If not admin, only return their own data
$users = [$this->user->find($user_id)];
}
if (empty($users)) {
$response = [
'status' => 'error',
'message' => 'No user data found.',
'data' => null
];
return $this->respond($response, 200);
}
$response = [
'status' => 'success',
'message' => 'User data retrieved successfully.',
'data' => $users
];
return $this->respond($response, 200);
}
//Create User Function
public function create()
{
$validationRules = [
'username' => 'required',
'name' => 'required',
'password_hash' => 'required',
'role' => 'required',
'status' => 'required',
];
// Add conditional validation for outlet_id when role is 'Outlet'
if ($this->request->getVar('role') === 'outlet') {
$validationRules['outlet_id'] = 'required|integer';
}
if (!$this->validate($validationRules)) {
$response = [
'status' => 'error',
'message' => 'Validation failed.',
'data' => $this->validator->getErrors()
];
return $this->respond($response, 422);
}
// Get menu permissions from request
$menuPermissions = $this->request->getVar('menuPermissions');
// Convert permissions to JSON string if they exist
$permissionsJson = null;
if ($menuPermissions) {
$permissionsJson = json_encode($menuPermissions);
if (json_last_error() !== JSON_ERROR_NONE) {
$response = [
'status' => 'error',
'message' => 'Invalid permissions format.',
'data' => null
];
return $this->respond($response, 400);
}
}
$userData = [
'username' => $this->request->getVar('username'),
'name' => $this->request->getVar('name'),
'password_hash' => md5($this->request->getVar('password_hash')),
'role' => $this->request->getVar('role'),
'status' => $this->request->getVar('status'),
'user_permissions' => $permissionsJson, // Store permissions as JSON string
];
// Only add outlet_id if role is 'Outlet'
if ($this->request->getVar('role') === 'outlet') {
$userData['outlet_id'] = $this->request->getVar('outlet_id');
}
$id = $this->user->insert($userData);
if ($id) {
$result = $this->user->find($id);
$response = [
'status' => 'success',
'message' => 'User created successfully.',
'data' => $result
];
return $this->respond($response, 201);
}
$response = [
'status' => 'error',
'message' => 'Failed to create user.',
'data' => null
];
return $this->respond($response, 500);
}
// show the required data.
public function show($id = null)
{
$user = $this->user->find($id);
if (!$user) {
$response = [
'status' => 'error',
'message' => 'User not found.',
'data' => null
];
return $this->respond($response, 404);
}
$response = [
'status' => 'success',
'message' => 'User retrieved successfully.',
'data' => $user
];
return $this->respond($response, 200);
}
// Update the data
public function update($id = null)
{
// Find existing user
$existingUser = $this->user->find($id);
if (!$existingUser) {
$response = [
'status' => 'error',
'message' => 'User not found.',
'data' => null
];
return $this->respond($response, 404);
}
// Get new data from request
$input = $this->request->getJSON(true); // Get JSON data
if (empty($input)) {
// fallback: try to get POST vars
$input = $this->request->getPost();
}
// Prepare data array only with fields that are present
$data = [];
// Map frontend field names to backend field names
if (isset($input['username'])) {
$data['username'] = $input['username'];
}
if (isset($input['name'])) {
$data['name'] = $input['name'];
}
if (isset($input['password'])) {
$data['password_hash'] = password_hash($input['password'], PASSWORD_DEFAULT);
}
// Handle userRoles -> role mapping
if (isset($input['role'])) {
$data['role'] = $input['role'];
// Handle outlet_id based on role change
if ($input['role'] === 'outlet') {
// Require outlet_id when changing to Outlet role
if (!isset($input['outlet_id'])) {
$response = [
'status' => 'error',
'message' => 'Outlet ID is required when role is Outlet.',
'data' => null
];
return $this->respond($response, 422);
}
$data['outlet_id'] = $input['outlet_id'];
} else {
// Clear outlet_id when changing to non-Outlet role
$data['outlet_id'] = null;
}
}
// Handle activeStatus -> status mapping
if (isset($input['activeStatus'])) {
$data['status'] = strtolower($input['activeStatus']);
}
// Handle outlet separately if role isn't being changed but user is Outlet
if (isset($input['outlet']) && $existingUser['role'] === 'outlet') {
$data['outlet_id'] = $input['outlet'];
}
// Handle menu permissions
if (isset($input['menuPermissions'])) {
$menuPermissions = $input['menuPermissions'];
$permissionsJson = null;
if ($menuPermissions && is_array($menuPermissions)) {
if (!empty($menuPermissions)) {
$permissionsJson = json_encode($menuPermissions);
if (json_last_error() !== JSON_ERROR_NONE) {
$response = [
'status' => 'error',
'message' => 'Invalid permissions format.',
'data' => null
];
return $this->respond($response, 400);
}
}
}
$data['user_permissions'] = $permissionsJson;
}
// If no fields to update, return an error
if (empty($data)) {
$response = [
'status' => 'error',
'message' => 'No data provided to update.',
'data' => null
];
return $this->respond($response, 400);
}
// Validate outlet_id if being set
if (isset($data['outlet_id']) && $data['outlet_id'] !== null) {
if (!$this->outletModel->find($data['outlet_id'])) {
$response = [
'status' => 'error',
'message' => 'Specified outlet does not exist.',
'data' => null
];
return $this->respond($response, 422);
}
}
// Add updated_at timestamp
$data['updated_at'] = date('Y-m-d H:i:s');
try {
// Update user
$this->user->update($id, $data);
// Return updated user data
$updatedUser = $this->user->find($id);
$response = [
'status' => 'success',
'message' => 'User updated successfully.',
'data' => $updatedUser
];
return $this->respond($response, 200);
} catch (\Exception $e) {
log_message('error', 'User update failed: ' . $e->getMessage());
$response = [
'status' => 'error',
'message' => 'Failed to update user.',
'data' => null
];
return $this->respond($response, 500);
}
}
// Delete User Function
public function delete($id = null)
{
$existingUser = $this->user->find($id);
if (!$existingUser) {
$response = [
'status' => 'error',
'message' => 'User not found.',
'data' => null
];
return $this->respond($response, 404);
}
$this->user->delete($id);
$response = [
'status' => 'success',
'message' => 'User deleted successfully.',
'data' => null
];
return $this->respond($response, 200);
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Controllers\Backend;
use App\Controllers\BaseController;
use App\Models\User;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
class UserRegisterController extends ResourceController
{
private $registerUser;
public function __construct()
{
$this->registerUser = new User();
}
public function index()
{
//
}
//Create User Function
public function create()
{
$validationRules = [
// Register User Data
'username'=> 'required',
'name'=> 'required',
'password_hash' => 'required',
'role' => 'required',
'status' => 'required',
];
$validation = $this->validate($validationRules);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$registerUserData = [
'username' => $this->request->getVar('username'),
'name' => $this->request->getVar('name'),
'password_hash' => md5($this->request->getVar('password_hash')),
'role' => $this->request->getVar('role'),
'status' => $this->request->getVar('statuss'),
];
if ($registerUserData)
{
$id = $this->registerUser->insert($registerUserData);
if ($id) {
$result = [
'id' => $id,
'username' => $this->request->getVar('username'),
'name' => $this->request->getVar('name'),
'password_hash' => md5($this->request->getVar('password_hash')),
'role' => $this->request->getVar('role'),
'status' => $this->request->getVar('status'),
];
$name = $this->request->getVar('register_user_name');
// $cemail = $this->request->getVar('register_user_email');
$message = "Hello $name,<br><br>";
$message .= "Thank you for your registration! We have received your registration form. Please allow us up to <strong>12 working hours</strong> to process your request. Our staff members will reach out to you shortly.<br><br>";
$message .= "<br><br>Thank you,<br>US PIZZA Sdn. Bhd.";
$subject = "Registration Submission Confirmation";
// $emailSent = SendMail::sendMail($name, $cemail, $message, $subject);
// if ($emailSent) {
// return $this->respond(['status' => 200, 'message' => 'Register user created successfully and Email sent successfully.', 'result' => $result]);
// } else {
// return $this->respond(['status' => 500, 'message' => 'Failed to send email.']);
// }
return $this->respond(['status' => 200, 'message' => 'User created successfully.', 'result' => $result]);
}
return $this->respond(['status' => 400, 'message' => 'Sorry! No user created.']);
}
}
}
File diff suppressed because it is too large Load Diff