Files
2025-08-07 16:34:00 +01:00

1995 lines
55 KiB
PHP

<?php
include_once 'core.php';
include_once 'config.php';
include_once 'license-model.php';
include_once 'user-model.php';
include_once 'calendar-model.php';
include_once 'project-model.php';
include_once 'report-model.php';
include_once 'location-model.php';
include_once 'accesslog-model.php';
include_once 'campaign-model.php';
include_once 'lib/google/oauth2.php';
include_once 'lib/google/drive.php';
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
function check_login()
{
if (!isset($_SESSION['is_logged_in'])) {
header("Location: /client/login");
exit;
}
}
Route::add('/', function () {
// Check if apikey is set in the GET parameters and validate it
if (!isset($_GET['apikey']) || empty($_GET['apikey'])) {
http_response_code(403);
echo json_encode(['error' => true, 'message' => 'Invalid API key']);
return;
}
$apikey = $_GET['apikey'];
// Check if relationship_num is set in the GET parameters and validate it
if (!isset($_GET['relationship_num']) || empty($_GET['relationship_num'])) {
http_response_code(403);
echo json_encode(['error' => true, 'message' => 'Invalid relationship_num']);
return;
}
$relationship_num = $_GET['relationship_num'];
// Get the user IP address
$user_ip = $_SERVER['REMOTE_ADDR'];
// Instantiate the LicenseModel
$licenseModel = new LicenseModel();
// Call the get_by_fields($where) function on the LicenseModel
$where = ['apikey' => $apikey];
$licenseModel = new LicenseModel();
$license = $licenseModel->get_one_by_fields($where);
// If the 'apikey' in the license array does not match the provided $apikey, print a JSON error with HTTP code 403
if ($license->apikey !== $apikey) {
http_response_code(403);
echo json_encode(['error' => true, 'message' => 'Invalid API key']);
exit;
}
if ($license->status !== 'active') {
http_response_code(401);
echo json_encode(['error' => true, 'message' => 'Suspended']);
exit;
}
// If the 'relationship_num' in the license array does not match the provided $relationship_num, print a JSON error with HTTP code 403
if ($license->relationship_num !== $relationship_num) {
http_response_code(403);
echo json_encode(['error' => true, 'message' => 'Invalid relationship number']);
exit;
}
// Instantiate the AccesslogModel
$accesslogModel = new AccesslogModel();
// Prepare the data array for the create() function
$data = [
'relationship_num' => $relationship_num,
'ip' => $user_ip,
'created_at' => date('Y-m-d H:i:s') // Current date and time
];
// Call the create($data) function on the AccesslogModel
$accesslogModel->create($data);
echo 'https://api.ghlessentials.com/ghl%20essentials/Call%20again%20button/callagain.js';
exit;
});
Route::add('/webhook', function () {
// Read the raw input data from the request body
$inputData = file_get_contents("php://input");
// Decode the JSON data
$jsonData = json_decode($inputData, true);
// Check if the JSON decoding was successful
if ($jsonData == null) {
// Handle JSON decoding error
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
return;
}
$key = 'oAXgvcyQumLwaLOcE2RLPlouB9dVVLobcFvFqXgzqKKbYmIrOJHe9hIDCE951n43aTwHV9mA1qLHCtnNt0AqViYIPLkLNxWpHL6kPqkXuRvsK0Qfl49TKbjuB9OqPLzWv0GpTPcaKusukq2JXDPCpR576mqpILX6iwSQlKgSDsCga9unTxONmcQkPhOkJFGj50sVYgLegQ6IPbQCBX5Y7mN6OI8SJ5BsCfwugLCdH1dOigiuJF5CY6RBg3YSZZrj';
// $headers = getallheaders();
// $api_key = $headers['HTTP_API_KEY'];
// Check if apikey is set in the GET parameters and validate it
if (!isset($_GET['api_key']) || empty($_GET['api_key'])) {
http_response_code(403);
echo json_encode(['error' => true, 'message' => 'Invalid API key', $_GET]);
return;
}
if ($_GET['api_key'] != $key) {
http_response_code(403);
echo json_encode(['error' => true, 'message' => 'Invalid APIs key']);
return;
}
// echo json_encode($_POST);
// exit;
// Instantiate the LicenseModel
$reportModel = new ReportModel();
$current_date = date('Y-m-d');
$subaccount = $jsonData['sub-account'];
// Call the get_by_fields($where) function on the LicenseModel
$where = ['date' => $current_date, 'project' => $subaccount];
$rep = $reportModel->get_by_fields($where);
$report = [];
foreach ($rep as $repor) {
$report = $repor;
}
// echo json_encode($report);
// echo json_encode($rep);
// exit;
if (!empty($report)) {
$workflow_type = $jsonData['type'];
switch ($workflow_type) {
case 'pickup':
$pickup = $report->pickup + 1;
$data = [
'pickup' => $pickup
];
# code...
$reportModel->edit($data, $report->id);
break;
case 'outgoing_dial':
$outgoing_dial = $report->outgoing_dial + 1;
$data = [
'outbound_dial' => $outgoing_dial
];
# code...
$reportModel->edit($data, $report->id);
# code...
break;
case 'convo':
$conversation = $report->conversation + 1;
$data = [
'conversation' => $conversation
];
# code...
$reportModel->edit($data, $report->id);
# code...
break;
case 'callback':
$callback = $report->callback + 1;
$data = [
'callback_request' => $callback
];
# code...
$reportModel->edit($data, $report->id);
# code...
break;
case 'new_lead':
$new_lead = $report->new_lead + 1;
$data = [
'new_lead' => $new_lead
];
# code...
$reportModel->edit($data, $report->id);
# code...
break;
case 'appointment':
$appointment = $report->booked_appointment + 1;
$data = [
'booked_appointment' => $appointment
];
# code...
$reportModel->edit($data, $report->id);
# code...
break;
}
echo json_encode(['error' => false, 'message' => 'Success']);
exit;
} else {
$workflow_type = $jsonData['type'];
switch ($workflow_type) {
case 'pickup':
$data = [
'pickup' => 1,
'project' => $subaccount,
'date' => $current_date
];
# code...
$reportModel->create($data);
break;
case 'outgoing_dial':
$data = [
'outbound_dial' => 1,
'project' => $subaccount,
'date' => $current_date
];
# code...
$reportModel->create($data);
# code...
break;
case 'convo':
$data = [
'conversation' => 1,
'project' => $subaccount,
'date' => $current_date
];
# code...
$reportModel->create($data);
# code...
break;
case 'callback':
$data = [
'callback_request' => 1,
'project' => $subaccount,
'date' => $current_date
];
# code...
$reportModel->create($data);
# code...
break;
case 'new_lead':
$data = [
'new_lead' => 1,
'project' => $subaccount,
'date' => $current_date
];
# code...
$reportModel->create($data);
# code...
break;
case 'appointment':
$data = [
'booked_appointment' => 1,
'project' => $subaccount,
'date' => $current_date
];
# code...
$reportModel->create($data);
# code...
break;
}
echo json_encode(['error' => false, 'message' => 'Success']);
exit;
}
echo json_encode(['error' => true, 'message' => 'Failed', $jsonData, $rep]);
exit;
}, 'post');
Route::add('/help', function () {
$str = <<<HEREDOC
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var key="apikey";
var relationship_num="#";
$.get('http://localhost:9000?apikey=' + key + '&relationship_num=' + relationship_num, function(data, status){
document.getElementById('tfp-call-again').src = data;
});
</script><script id="tfp-call-again"></script>
HEREDOC;
echo htmlentities($str);
exit;
}, 'get');
Route::add('/admin/login', function () {
include_once __DIR__ . '/login.php';
}, 'get');
Route::add('/admin/logout', function () {
unset($_SESSION["is_logged_in"]);
unset($_SESSION['role']);
unset( $_SESSION['user']);
header('Location: /admin/login');
}, 'get');
Route::add('/admin/login', function () {
$error = false;
$data = [];
if (empty($_POST['password']) || empty($_POST['email'])) {
$error = true;
// include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/login.php';
// include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} else {
// Collect form data
$raw_password = $_POST['password'];
$email = $_POST['email'];
// Prepare data array
$data = [
'password' => password_hash($raw_password, PASSWORD_BCRYPT),
'email' => $email,
];
// Insert data into the database using LicenseModel
$userModel = new UserModel();
$result = $userModel->get_by_field('email', $email);
// var_dump($result);exit;
if ($result) {
if (password_verify($raw_password, $result['password']) && $result['status'] == 'active' && $result['role'] == 'admin') {
$_SESSION['is_logged_in'] = true;
$_SESSION['role'] = $result['role'];
$_SESSION['user'] = $result['id'];
header('Location: /admin/accesslog');
} else {
$error = true;
include_once __DIR__ . '/login.php';
}
}
$error = true;
include_once __DIR__ . '/login.php';
}
}, 'post');
Route::add('/admin/users', function () {
check_login();
$format = isset($_GET['format']) ? $_GET['format'] : 'json';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$per_page = isset($_GET['size']) ? intval($_GET['size']) : 10;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$direction = isset($_GET['direction']) ? $_GET['direction'] : 'ASC';
$userModel = new UserModel();
$data = [
'page_title' => 'Users'
];
$where = [];
$result = $userModel->get_paginated($page, $per_page, $where, $sort, $direction);
if ($result) {
if ($format == 'json') {
$data = array_merge($data, $result);
}
}
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/userListing.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/users/add', function () {
check_login();
$error = false;
$data = [
'page_title' => 'Users'
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/userAdd.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/users/add', function () {
check_login();
$error = false;
$data = [
'page_title' => 'Users'
];
if (empty($_POST['password']) || empty($_POST['email']) || empty($_POST['company'])) {
$error = true;
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/userAdd.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} else {
// Collect form data
$password = $_POST['password'];
$email = $_POST['email'];
$role = $_POST['role'];
$company = $_POST['company'];
// Prepare data array
$data = [
'password' => password_hash($password, PASSWORD_BCRYPT),
'email' => $email,
'role' => $role,
'status' => 'active',
'company' => $company,
];
// Insert data into the database using LicenseModel
$userModel = new UserModel();
$userModel->create($data);
header('Location: /admin/users');
}
}, 'post');
Route::add('/admin/users/edit/([0-9]+)', function ($id) {
check_login();
$error = false;
$userModel = new UserModel();
$model = $userModel->get($id);
if (!$model) {
header('Location: /admin/users');
exit;
}
$data = [
'page_title' => 'Users',
'model' => $model
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/userEdit.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/users/edit/([0-9]+)', function ($id) {
check_login();
$error = false;
$userModel = new UserModel();
$model = $userModel->get($id);
if (!$model) {
header('Location: /admin/users');
exit;
}
$data = [
'page_title' => 'Users',
'id' => $id
];
if (empty($_POST['email']) || empty($_POST['status'])) {
$error = true;
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/userEdit.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} else {
// Collect form data
$password = isset($_POST['password']) ? $_POST['password'] : '';
$email = $_POST['email'];
$status = $_POST['status'];
$company = $_POST['company'];
// Prepare data array
$data = [
'email' => $email,
'status' => $status,
'company' => $company
];
if (strlen($password) > 0) {
$data['password'] = password_hash($password, PASSWORD_BCRYPT);
}
// Insert data into the database using LicenseModel
$userModel = new UserModel();
$userModel->edit($data, $id);
header('Location: /admin/users');
}
}, 'post');
Route::add('/admin/users/delete/([0-9]+)', function ($id) {
check_login();
$userModel = new UserModel();
$userModel->real_delete($id);
header('Location: /admin/users');
}, 'get');
Route::add('/admin/license', function () {
check_login();
$format = isset($_GET['format']) ? $_GET['format'] : 'json';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$cursor_id = isset($_GET['cursor']) ? intval($_GET['cursor']) : 0;
$per_page = isset($_GET['size']) ? intval($_GET['size']) : 10;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$direction = isset($_GET['direction']) ? $_GET['direction'] : 'ASC';
$relationship_num = isset($_GET['relationship_num']) ? $_GET['relationship_num'] : '';
$email_search = isset($_GET['email']) ? trim($_GET['email']) : '';
$licenseModel = new LicenseModel();
$data = [
'page_title' => 'License',
'relationship_num' => $relationship_num,
'email_search' => $email_search
];
$where = [];
if ($relationship_num != '') {
// $where['relationship_num'] = '"' . $relationship_num . '"';
// $where[] = '"' . $relationship_num . '"';
$where[] = "relationship_num = '" . addslashes($relationship_num) . "'";
}
// Add fuzzy email search using LIKE
if ($email_search != '') {
$where[] = "email LIKE '%" . addslashes($email_search) . "%'";
}
// Use cursor-based pagination instead of offset-based
$result = $licenseModel->get_cursor_paginated($page, $per_page, $where, $sort, $direction, $cursor_id);
if ($result) {
if ($format == 'json') {
$data = array_merge($data, $result);
}
}
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/licenseListing.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/accesslog', function () {
check_login();
$format = isset($_GET['format']) ? $_GET['format'] : 'json';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$per_page = isset($_GET['size']) ? intval($_GET['size']) : 10;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$direction = isset($_GET['direction']) ? $_GET['direction'] : 'ASC';
$relationship_num = isset($_GET['relationship_num']) ? $_GET['relationship_num'] : '';
$accesslogModel = new AccesslogModel();
$data = [
'page_title' => 'Access Log',
'relationship_num' => $relationship_num
];
$where = [];
if ($relationship_num != '') {
$where['relationship_num'] = '"' . $relationship_num . '"';
}
$result = $accesslogModel->get_paginated($page, $per_page, $where, 'id', 'DESC');
if ($result) {
if ($format == 'json') {
$data = array_merge($data, $result);
}
}
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/accessListing.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/license/add', function () {
check_login();
$error = false;
$data = [
'page_title' => 'License'
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/licenseAdd.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/license/edit/([0-9]+)', function ($id) {
check_login();
$error = false;
$licenseModel = new LicenseModel();
$model = $licenseModel->get($id);
if (!$model) {
header('Location: /admin/license');
exit;
}
$data = [
'page_title' => 'License',
'model' => $model
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/licenseEdit.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/license/add', function () {
check_login();
$error = false;
$data = [
'page_title' => 'License'
];
if (empty($_POST['relationship_num']) || empty($_POST['email'])) {
$error = true;
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/licenseAdd.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} else {
// Collect form data
$relationship_num = $_POST['relationship_num'];
$email = $_POST['email'];
// Generate apikey
$current_date = date('Y-m-d H:i:s');
$random_num = mt_rand(); // Generate a random number
$apikey_string = $current_date . $relationship_num . $random_num;
$apikey = md5($apikey_string);
// Prepare data array
$data = [
'relationship_num' => $relationship_num,
'email' => $email,
'apikey' => $apikey,
'ip' => '', // Leaving IP as blank for now
'status' => 'active',
'created_at' => $current_date
];
// Insert data into the database using LicenseModel
$licenseModel = new LicenseModel();
$licenseModel->create($data);
header('Location: /admin/license');
}
}, 'post');
Route::add('/admin/license/edit/([0-9]+)', function ($id) {
check_login();
$error = false;
$licenseModel = new LicenseModel();
$model = $licenseModel->get($id);
if (!$model) {
header('Location: /admin/license');
exit;
}
$data = [
'page_title' => 'License',
'id' => $id
];
if (empty($_POST['relationship_num']) || empty($_POST['email']) || empty($_POST['apikey']) || empty($_POST['status'])) {
$error = true;
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/licenseEdit.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} else {
// Collect form data
$relationship_num = $_POST['relationship_num'];
$email = $_POST['email'];
$status = $_POST['status'];
$apikey = $_POST['apikey'];
$ip = $_POST['ip'];
// Generate apikey
$current_date = date('Y-m-d H:i:s');
// Prepare data array
$data = [
'relationship_num' => $relationship_num,
'email' => $email,
'apikey' => $apikey,
'ip' => $ip,
'status' => $status
];
// Insert data into the database using LicenseModel
$licenseModel = new LicenseModel();
$licenseModel->edit($data, $id);
header('Location: /admin/license');
}
}, 'post');
Route::add('/admin/location', function () {
check_login();
$format = isset($_GET['format']) ? $_GET['format'] : 'json';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$per_page = isset($_GET['size']) ? intval($_GET['size']) : 10;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$direction = isset($_GET['direction']) ? $_GET['direction'] : 'ASC';
$name = isset($_GET['name']) ? $_GET['name'] : '';
$locationModel = new LocationModel();
$data = [
'page_title' => 'Location',
'name' => $name
];
$where = [];
if ($name != '') {
$where['name'] = '"' . $name . '"';
}
$result = $locationModel->get_paginated($page, $per_page, $where, $sort, $direction);
if ($result) {
if ($format == 'json') {
$data = array_merge($data, $result);
}
}
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/locationListing.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/location/add', function () {
check_login();
$error = false;
$data = [
'page_title' => 'Location'
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/locationAdd.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/report/webhook/send/([0-9]+)', function ($id) {
check_login();
$error = false;
$data = [
'page_title' => 'Location'
];
$reportModel = new ReportModel();
$model = $reportModel->get($id);
$locationModel = new LocationModel();
$location = $locationModel->get($model->location_id);
$params= [
"name" => $location->name,
"date" => $model->date,
"type" => $model->type,
"report" => $reportModel->csvToObject($model->report)
];
$rData = json_encode($params);
$webhook = $location->webhook;
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $webhook,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $rData,
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if(isset($_SERVER['HTTP_REFERER'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
} else {
header('Location: admin/report');
}
}, 'post');
Route::add('/admin/location/edit/([0-9]+)', function ($id) {
check_login();
$error = false;
$locationModel = new LocationModel();
$model = $locationModel->get($id);
if (!$model) {
header('Location: /admin/location');
exit;
}
$data = [
'page_title' => 'Location',
'model' => $model
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/locationEdit.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/mysql', function () {
include_once __DIR__ . 'adminer-4.8.1-mysql-en.php';
}, 'get');
Route::add('/admin/location/add', function () {
check_login();
$error = false;
$data = [
'page_title' => 'Location'
];
if (empty($_POST['name']) || empty($_POST['apikey']) || empty($_POST['location_id'])) {
$error = true;
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/locationAdd.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} else {
// Collect form data
$name = $_POST['name'];
$apikey = $_POST['apikey'];
$webhook = $_POST['webhook'];
$location_id = $_POST['location_id'];
// Prepare data array
$data = [
'name' => $name,
'apikey' => $apikey,
'webhook' => $webhook,
'location_id' => $location_id,
'created_at' => $current_date
];
// Insert data into the database using LicenseModel
$locationModel = new LocationModel();
$locationModel->create($data);
header('Location: /admin/location');
}
}, 'post');
Route::add('/admin/location/edit/([0-9]+)', function ($id) {
check_login();
$error = false;
$locationModel = new LocationModel();
$model = $locationModel->get($id);
if (!$model) {
header('Location: /admin/license');
exit;
}
$data = [
'page_title' => 'Location',
'id' => $id
];
if (empty($_POST['name']) || empty($_POST['apikey']) || empty($_POST['location_id']) ) {
$error = true;
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/locationEdit.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} else {
// Collect form data
$name = $_POST['name'];
$apikey = $_POST['apikey'];
$webhook = $_POST['webhook'];
$location_id = $_POST['location_id'];
// Generate apikey
$current_date = date('Y-m-d H:i:s');
// Prepare data array
$data = [
'name' => $name,
'apikey' => $apikey,
'webhook' => $webhook,
'location_id' => $location_id,
];
// Insert data into the database using LicenseModel
$locationModel = new LocationModel();
$locationModel->edit($data, $id);
header('Location: /admin/location');
}
}, 'post');
Route::add('/admin/project', function () {
check_login();
$format = isset($_GET['format']) ? $_GET['format'] : 'json';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$per_page = isset($_GET['size']) ? intval($_GET['size']) : 15;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$direction = isset($_GET['direction']) ? $_GET['direction'] : 'ASC';
$project_search = isset($_GET['project_search']) ? $_GET['project_search'] : '';
$webhook_search = isset($_GET['webhook_search']) ? $_GET['webhook_search'] : '';
$projectModel = new ProjectModel();
$data = [
'page_title' => 'Project',
'project_search' => $project_search,
'webhook_search' => $webhook_search
];
$where = [];
// Add fuzzy search for project_name
if ($project_search != '') {
$where[] = "project_name LIKE '%" . addslashes($project_search) . "%'";
}
// Add fuzzy search for webhook
if ($webhook_search != '') {
$where[] = "webhook LIKE '%" . addslashes($webhook_search) . "%'";
}
$result = $projectModel->get_paginated($page, $per_page, $where, 'id', 'DESC');
// echo json_encode($result);
if ($result) {
if ($format == 'json') {
$data = array_merge($data, $result);
}
}
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/projectListing.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/project/add', function () {
check_login();
$error = false;
$data = [
'page_title' => 'Project'
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/projectAdd.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/project/edit/([0-9]+)', function ($id) {
check_login();
$error = false;
$projectModel = new ProjectModel();
$model = $projectModel->get($id);
if (!$model) {
header('Location: /admin/project');
exit;
}
$data = [
'page_title' => 'Project',
'model' => $model
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/projectEdit.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/project/add', function () {
check_login();
$error = false;
$data = [
'page_title' => 'Project'
];
if (empty($_POST['project_name']) || empty($_POST['slot']) || empty($_POST['days']) || empty($_POST['score_threshold']) || empty($_POST['actual_score']) || empty($_POST['webhook']) || empty($_POST['calendar_id']) || empty($_POST['location'])) {
$error = true;
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/projectAdd.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} else {
// Collect form data
$project_name = $_POST['project_name'];
$slot = $_POST['slot'];
$days = $_POST['days'];
// $alert = $_POST['alert'];
$score_threshold = $_POST['score_threshold'];
$actual_score = $_POST['actual_score'];
$webhook = $_POST['webhook'];
// $webhook_payload = $_POST['webhook_payload'];
$calendar_id = $_POST['calendar_id'];
$location = $_POST['location'];
$current_date = date('Y-m-d H:i:s');
$webhook_payload = array(
"project_name" => $project_name,
);
$webhook_payload = json_encode($webhook_payload);
// echo $webhook_payload;
// exit;
// function create_calendar_id()
// {
// $dt = microtime(true) * 1000; // Get current time in milliseconds
// $uuid = preg_replace_callback('/[xy]/', function ($matches) use ($dt) {
// $r = ($dt + mt_rand() * 16) % 16 | 0;
// $dt = floor($dt / 16);
// return ($matches[0] == 'x' ? dechex($r) : (dechex($r & 0x3 | 0x8)));
// }, 'xxxxxxxxxx');
// return $uuid;
// }
// function create_calendar_id()
// {
// $base = uniqid(); // Use uniqid as a base
// $uuid = preg_replace_callback('/[a-f0-9]/', function ($matches) {
// return dechex(mt_rand(0, 15));
// }, $base);
// return $uuid;
// }
// $config = MkdConfig::get_instance()->get_config();
// $calendar = $config['domain-name'] . "/admin/calendar/";
// $calendars = create_calendar_id();
// Prepare data array
// $calendar_data = [
// 'slot' => $slot,
// 'days' => $days,
// 'calendar' => $calendars,
// 'created_at' => $current_date
// ];
// $calendarModel = new CalendarModel();
// $calendarModel->create($calendar_data);
// echo $test;
// exit;
// if ($score_threshold < $actual_score) {
// $alert = "Yes";
// } else {
$alert = "Off";
// }
$data = [
'project_name' => $project_name,
'slot' => $slot,
'days' => $days,
'alert' => $alert,
'score_threshold' => $score_threshold,
'actual_score' => $actual_score,
'webhook' => $webhook,
'payload' => $webhook_payload,
'calendar' => $calendar_id,
'location' => $location,
'created_at' => $current_date
];
// Insert data into the database using LicenseModel
$projectModel = new ProjectModel();
$projectModel->create($data);
echo 'Project Added';
// header('Location: /admin/project');
}
}, 'post');
Route::add('/alert-toggle', function () {
check_login();
$error = false;
$data = [
'page_title' => 'Project'
];
$id = $_POST['projectId'];
$alert = $_POST['selectedValue'];
$data = [
'alert' => $alert
];
// Insert data into the database using LicenseModel
$projectModel = new ProjectModel();
$edit = $projectModel->edit($data, (int)$id);
// header('Location: /admin/project');
echo $edit;
}, 'post');
Route::add('/admin/project/edit/([0-9]+)', function ($id) {
check_login();
$error = false;
$projectModel = new ProjectModel();
$model = $projectModel->get($id);
if (!$model) {
header('Location: /admin/project');
exit;
}
$data = [
'page_title' => 'Project',
'id' => $id
];
if (empty($_POST['project_name']) || empty($_POST['slot']) || empty($_POST['days']) || empty($_POST['score_threshold']) || empty($_POST['actual_score']) || empty($_POST['webhook']) || empty($_POST['webhook_payload']) || empty($_POST['calendar_id']) || empty($_POST['location'])) {
$error = true;
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/projectEdit.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} else {
// Collect form data
$project_name = $_POST['project_name'];
$slot = $_POST['slot'];
$days = $_POST['days'];
// $alert = $_POST['alert'];
$score_threshold = $_POST['score_threshold'];
$actual_score = $_POST['actual_score'];
$webhook = $_POST['webhook'];
$webhook_payload = $_POST['webhook_payload'];
$calendar_id = $_POST['calendar_id'];
$location = $_POST['location'];
// $calendar_id = $_POST['calendar_id'];
$current_date = date('Y-m-d H:i:s');
// function create_calendar_id()
// {
// $dt = microtime(true) * 1000; // Get current time in milliseconds
// $uuid = preg_replace_callback('/[xy]/', function ($matches) use ($dt) {
// $r = ($dt + mt_rand() * 16) % 16 | 0;
// $dt = floor($dt / 16);
// return ($matches[0] == 'x' ? dechex($r) : (dechex($r & 0x3 | 0x8)));
// }, 'xxxxxxxxxx');
// return $uuid;
// }
// $config = MkdConfig::get_instance()->get_config();
// $calendar = $config['domain-name'] . "/admin/calendar/";
// $calendars = create_calendar_id();
// $calendarModel = new CalendarModel();
// $calModel = $calendarModel->get_by_field("calendar", $calendar);
// echo json_encode($calModel);
// echo $calModel->id;
// exit;
// Prepare data array
// $calendar_data = [
// // 'slot' => $slot,
// 'slot' => $slot,
// 'days' => $days,
// // 'alert' => $alert,
// ];
// $calendarModel = new CalendarModel();
// $calendarModel->edit($calendar_data, $calModel->id);
// if ($score_threshold < $actual_score) {
// $alert = "Yes";
// } else {
// $alert = "No";
// }
$data = [
'project_name' => $project_name,
'slot' => $slot,
'days' => $days,
// 'alert' => $alert,
'score_threshold' => $score_threshold,
'actual_score' => $actual_score,
'webhook' => $webhook,
'calendar' => $calendar_id,
'location' => $location,
'payload' => $webhook_payload,
];
// Insert data into the database using LicenseModel
$projectModel = new ProjectModel();
$projectModel->edit($data, $id);
// header('Location: /admin/project');
// echo 'done';
}
}, 'post');
Route::add('/admin/calendar/([a-zA-Z0-9]+)', function ($calendar_id) {
check_login();
$error = false;
$calendarModel = new CalendarModel();
$model = $calendarModel->get_by_fields(["calendar" => $calendar_id]);
$data = [
'page_title' => 'Calendar',
'model' => $model,
"calendar" => $calendar_id
];
// $numberOfDays = 7; // Change this as needed
// $availableTimeSlots = ['10:00', '11:00', '14:00', '16:00']; // Change this as needed
// $events = [];
// foreach ($availableTimeSlots as $timeSlot) {
// for ($i = 1; $i <= $numberOfDays; $i++) {
// $event = [
// 'title' => 'Available',
// 'start' => date('Y-m-d', strtotime("+$i day")) . 'T' . $timeSlot,
// 'end' => date('Y-m-d', strtotime("+$i day")) . 'T' . $timeSlot,
// ];
// array_push($events, $event);
// }
// }
// echo json_encode($events);
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/calendar.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/calendar', function () {
check_login();
$error = false;
// $data = [
// 'page_title' => 'Calendar'
// ];
// if (empty($_POST['project_name']) || empty($_POST['slot'])) {
// $error = true;
// include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
// include_once __DIR__ . '/projectAdd.php';
// include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
// } else {
// Collect form data
$calendar = $_POST['calendar'];
$calendarModel = new CalendarModel();
$model = $calendarModel->get_by_fields(["calendar" => $calendar]);
$mod = [];
foreach ($model as $slot) {
$mod = [
'slot' => $slot['slot'],
'days' => $slot['days'],
'created_at' => $slot['created_at']
];
}
echo json_encode($mod);
// }
}, 'post');
Route::add('/admin/duplicate', function () {
check_login();
$error = false;
// $data = [
// 'page_title' => 'Calendar'
// ];
// if (empty($_POST['project_name']) || empty($_POST['slot'])) {
// $error = true;
// include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
// include_once __DIR__ . '/projectAdd.php';
// include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
// } else {
// Collect form data
$id = $_POST['project_id'];
$calendar_id = $_POST['calendar_id'];
$current_date = date('Y-m-d H:i:s');
$projectModel = new ProjectModel();
$model = $projectModel->get($id);
// echo $model;
// exit;
// Use regular expression to check if the variable ends with a number within brackets
if (preg_match('/\((\d+)\)$/', $model->project_name, $matches)) {
// Extract the number and increment it
$number = $matches[1] + 1;
// Replace the old number with the incremented number
$modifiedVariable = preg_replace('/\(\d+\)$/', "($number)", $model->project_name);
// echo $modifiedVariable;
// Remove content within parentheses
$modifiedVariable2 = preg_replace('/\(\d+\)/', '', $model->project_name);
} else {
// If no number within brackets at the end, append "(1)"
$modifiedVariable2 = $model->project_name;
// echo $modifiedVariable;
}
$model2 = $projectModel->get_like('project_name', $modifiedVariable2);
if (!empty($model2)) {
foreach ($model2 as $mod) {
// Use regular expression to check if the variable ends with a number within brackets
if (preg_match('/\((\d+)\)$/', $mod->project_name, $matches)) {
// Extract the number and increment it
$number = $matches[1] + 1;
// Replace the old number with the incremented number
$modifiedVariable = preg_replace('/\(\d+\)$/', "($number)", $mod->project_name);
// echo $modifiedVariable;
} else {
// If no number within brackets at the end, append "(1)"
$modifiedVariable = $mod->project_name . "(1)";
// echo $modifiedVariable;
}
// $modifiedVariable = $mod->project_name;
}
}
// echo json_encode($model2);
// exit;
$data = [
'project_name' => $modifiedVariable,
'slot' => $model->slot,
'days' => $model->days,
'alert' => $model->alert,
'score_threshold' => $model->score_threshold,
'actual_score' => $model->actual_score,
'webhook' => $model->webhook,
'location' => $model->location,
'payload' => $model->payload,
'calendar' => $calendar_id,
'created_at' => $current_date
];
// Insert data into the database using LicenseModel
$projectModel->create($data);
echo 'Project Duplicated';
// }
}, 'post');
Route::add('/admin/report', function () {
check_login();
$format = isset($_GET['format']) ? $_GET['format'] : 'json';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$per_page = isset($_GET['size']) ? intval($_GET['size']) : 10;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$direction = isset($_GET['direction']) ? $_GET['direction'] : 'ASC';
$date = isset($_GET['date']) ? $_GET['date'] : '';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';
$project = isset($_GET['project']) ? $_GET['project'] : '';
$reportModel = new ReportModel();
$data = [
'page_title' => 'Report',
'date' => $date,
"start_date" => $start_date,
"end_date" => $end_date,
"project" => $project
];
$where = [];
if ($date != '' && empty($start_date) && empty($end_date)) {
$where['date'] = '"' . $date . '"';
}
if (!empty($start_date) && !empty($end_date)) {
$where[] = "date BETWEEN '" . $start_date . "' AND '" . $end_date . "'";
}
if (!empty($start_date) && empty($end_date)) {
$where[] = "date >= '" . $start_date . "'";
}
if (empty($start_date) && !empty($end_date)) {
$where[] = "date <= '" . $end_date . "'";
}
if($project != '') {
$where[] = "project LIKE '%" . addslashes($project) . "%'";
}
$result = $reportModel->get_paginated($page, $per_page, $where, 'id', 'DESC');
// echo json_encode($result);
if ($result) {
if ($format == 'json') {
$data = array_merge($data, $result);
}
}
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/reportListing.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/report/csv', function () {
check_login();
$format = isset($_GET['format']) ? $_GET['format'] : 'json';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$per_page = isset($_GET['size']) ? intval($_GET['size']) : 10;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$direction = isset($_GET['direction']) ? $_GET['direction'] : 'ASC';
$date = isset($_GET['date']) ? $_GET['date'] : '';
$reportModel = new ReportModel();
$data = [
'page_title' => 'Project',
];
$where = [];
if ($date != '') {
$where['date'] = '"' . $date . '"';
}
$result = $reportModel->get_all($where);
// echo json_encode($result);
if ($result) {
if ($format == 'json') {
$data = array_merge($data, $result);
}
if ($format == 'csv') {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="report.csv"');
$clean_list = [];
foreach ($result as $key => $value) {
$clean_list_entry = [];
$clean_list_entry['id'] = $value->id;
$clean_list_entry['project'] = $value->project;
$clean_list_entry['date'] = $value->date;
$clean_list_entry['ghl_user_id'] = $value->ghl_user_id;
$clean_list_entry['username'] = $value->username;
$clean_list_entry['new_lead'] = $value->new_lead;
$clean_list_entry['outbound_dial'] = $value->outbound_dial;
$clean_list_entry['pickup'] = $value->pickup;
$clean_list_entry['conversation'] = $value->conversation;
$clean_list_entry['booked_appointment'] = $value->booked_appointment;
$clean_list_entry['callback_request'] = $value->callback_request;
$clean_list[] = $clean_list_entry;
}
$column_fields = [
'ID', 'Project', 'Date', 'GHL User ID', 'GHL Username', 'New Lead', 'Outbound Dial', 'Pickup', 'Conversation', 'Booked Appointment', 'Callback Request'
];
$csv = implode(",", $column_fields) . "\n";
// $fields = array_filter($this->get_field_column());
foreach ($clean_list as $row) {
$row_csv = [];
foreach ($row as $key => $column) {
// if (in_array($key, $fields))
// {
$row_csv[] = '"' . $column . '"';
// }
}
$csv = $csv . implode(',', $row_csv) . "\n";
}
echo $csv;
exit();
}
}
}, 'get');
Route::add('/admin/license/delete/([0-9]+)', function ($id) {
check_login();
$licenseModel = new LicenseModel();
$licenseModel->real_delete($id);
header('Location: /admin/license');
}, 'get');
Route::add('/admin/license/list/multiselect', function () {
check_login();
$licenseModel = new LicenseModel();
if (isset($_POST['delete'])) {
if (isset($_POST['selected_items']) && !empty($_POST['selected_items'])) {
$ids = explode(',', $_POST['selected_items']);
$ids = array_map('intval', $ids); // Sanitize IDs
$ids_string = implode(', ', $ids);
$licenseModel->real_delete_by_fields([
"id IN ($ids_string)"
]);
}
header('Location: /admin/license');
exit;
}
// If no valid action, redirect back
header('Location: /admin/license');
exit;
}, 'post');
Route::add('/admin/location/delete/([0-9]+)', function ($id) {
check_login();
$locationModel = new LocationModel();
$locationModel->real_delete($id);
header('Location: /admin/location');
}, 'get');
Route::add('/admin/accesslog/delete/([0-9]+)', function ($id) {
check_login();
$accesslogModel = new AccesslogModel();
$accesslogModel->real_delete($id);
header('Location: /admin/accesslog');
}, 'get');
Route::add('/admin/project/delete/([0-9]+)', function ($id) {
check_login();
$projectModel = new ProjectModel();
$projectModel->real_delete($id);
header('Location: /admin/project');
}, 'get');
Route::add('/admin/project/list/multiselect', function () {
check_login();
$error = false;
$projectModel = new ProjectModel();
if (isset($_POST['delete'])) {
$ids = implode(', ', array_map('intval', $_POST['selected']));
$projectModel->real_delete_by_fields([
"id IN ($ids)"
]);
header('Location: /admin/project');
}
if (isset($_POST['edit'])) {
$ids = implode(',', array_map('intval', $_POST['selected']));
$data = [
'page_title' => 'Project',
'ids' => "$ids"
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/projectEditMulti.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
exit;
}
if (isset($_POST['multiedit'])) {
if (empty($_POST['project_name']) || empty($_POST['slot']) || empty($_POST['days']) || empty($_POST['score_threshold']) || empty($_POST['actual_score']) || empty($_POST['webhook']) || empty($_POST['webhook_payload']) || empty($_POST['calendar_id']) || empty($_POST['location'])) {
$error = true;
$ids = implode(',', array_map('intval', $_POST['selected']));
$data = [
'page_title' => 'Project',
'ids' => "$ids"
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/projectEditMulti.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
exit;
} else {
// Collect form data
$project_name = $_POST['project_name'];
$slot = $_POST['slot'];
$days = $_POST['days'];
// $alert = $_POST['alert'];
$score_threshold = $_POST['score_threshold'];
$actual_score = $_POST['actual_score'];
$webhook = $_POST['webhook'];
$webhook_payload = $_POST['webhook_payload'];
$calendar_id = $_POST['calendar_id'];
$location = $_POST['location'];
// $calendar_id = $_POST['calendar_id'];
$current_date = date('Y-m-d H:i:s');
$data = [
'project_name' => $project_name,
'slot' => $slot,
'days' => $days,
// 'alert' => $alert,
'score_threshold' => $score_threshold,
'actual_score' => $actual_score,
'webhook' => $webhook,
'calendar' => $calendar_id,
'location' => $location,
'payload' => $webhook_payload,
];
$edit_ids = explode(",", $_POST['ids']);
foreach($edit_ids as $id) {
$projectModel = new ProjectModel();
$projectModel->edit($data, $id);
}
header('Location: /admin/project');
exit;
}
}
}, 'post');
// Client
// Google Drive OAuth routes
Route::add('/drive/authorize', function() {
check_login();
$config = MkdConfig::get_instance()->get_config();
$oauth = new \Lib\Google\GoogleOAuth2(
$config['google_client_id'],
$config['google_client_secret'],
$config['google_redirect_uri']
);
$drive = new \Lib\Google\GoogleDrive($oauth);
$url = $drive->getAuthorizationUrl([
'state' => $_SESSION['user'] . '|' . $_SESSION['role']
]);
header('Location: ' . $url);
exit;
}, 'get');
Route::add('/google/drive/callback', function() {
$config = MkdConfig::get_instance()->get_config();
if (!isset($_GET['code'])) {
header('Location: /' . $_SESSION['role'] . '/campaign?error=auth_failed');
exit;
}
list($userId, $role) = explode('|', $_GET['state']);
$oauth = new \Lib\Google\GoogleOAuth2(
$config['google_client_id'],
$config['google_client_secret'],
$config['google_redirect_uri']
);
try {
$tokens = $oauth->exchangeCode($_GET['code']);
$userModel = new UserModel();
$userModel->edit([
'drive_access_token' => $tokens['access_token'],
'drive_refresh_token' => $tokens['refresh_token']
], $userId);
header('Location: /' . $role . '/campaign?success=connected');
} catch (\Exception $e) {
header('Location: /' . $role . '/campaign?error=auth_failed');
}
exit;
}, 'get');
Route::add('/drive/files', function() {
check_login();
$config = MkdConfig::get_instance()->get_config();
$folderId = isset($_GET['folderId']) ? $_GET['folderId'] : null;
$userModel = new UserModel();
$user = $userModel->get($_SESSION['user']);
if (!$user->drive_refresh_token) {
http_response_code(401);
echo json_encode(['error' => 'Not authorized']);
exit;
}
$oauth = new \Lib\Google\GoogleOAuth2(
$config['google_client_id'],
$config['google_client_secret'],
$config['google_redirect_uri']
);
$oauth->setRefreshToken($user->drive_refresh_token);
$oauth->refreshAccessToken();
$drive = new \Lib\Google\GoogleDrive($oauth);
try {
// Pass the folderId and mime types as options
$files = $drive->listFiles($folderId === 'root' ? null : $folderId, [
'mimeTypes' => [
'application/vnd.google-apps.folder',
'application/vnd.google-apps.spreadsheet'
]
]);
echo json_encode(['files' => $files['files']]);
} catch (\Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
exit;
}, 'get');
// Add admin campaign routes
Route::add('/admin/campaign', function () {
check_login();
$format = isset($_GET['format']) ? $_GET['format'] : 'json';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = isset($_GET['size']) ? intval($_GET['size']) : 10;
$campaignModel = new CampaignModel();
$data = [
'page_title' => 'Campaign',
'date' => isset($_GET['date']) ? $_GET['date'] : ''
];
$where = [];
if (!empty($data['date'])) {
$where['date'] = '"' . $data['date'] . '"';
}
$result = $campaignModel->get_paginated($page, $per_page, $where, 'id', 'DESC');
if ($result) {
if ($format == 'json') {
$data = array_merge($data, $result);
}
}
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/campaignListing.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
// Reuse the same campaign routes but with admin prefix
Route::add('/admin/campaign/add', function () {
check_login();
$data = ['page_title' => 'Campaign'];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/campaignAdd.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/campaign/add', function () {
check_login();
if (empty($_POST['name']) || empty($_POST['file_id'])) {
header('Location: /admin/campaign/add');
exit;
}
$data = [
'name' => $_POST['name'],
'file_id' => $_POST['file_id'],
'user_id' => $_SESSION['user'],
'created_at' => date('Y-m-d H:i:s')
];
$campaignModel = new CampaignModel();
$campaignModel->create($data);
header('Location: /admin/campaign');
}, 'post');
// Add other admin campaign routes (edit, delete, view) similarly
// Add admin campaign view route
Route::add('/admin/campaign/view/([0-9]+)', function ($id) {
check_login();
$campaignModel = new CampaignModel();
$campaign = $campaignModel->get($id);
if (!$campaign) {
header('Location: /admin/campaign');
exit;
}
$config = MkdConfig::get_instance()->get_config();
$userModel = new UserModel();
$user = $userModel->get($campaign->user_id);
if (!$user->drive_refresh_token) {
header('Location: /admin/campaign?error=drive_not_connected');
exit;
}
$oauth = new \Lib\Google\GoogleOAuth2(
$config['google_client_id'],
$config['google_client_secret'],
$config['google_redirect_uri']
);
$oauth->setRefreshToken($user->drive_refresh_token);
$oauth->refreshAccessToken();
$drive = new \Lib\Google\GoogleDrive($oauth);
try {
// Download as CSV
$content = $drive->downloadFile(
$campaign->file_id,
'text/csv'
);
// Convert TSV/CSV to array of objects
$rows = array_map('str_getcsv', explode("\n", $content));
$headers = array_map(function($header) {
return str_replace(' ', '_', trim(strtolower($header)));
}, array_shift($rows));
$campaignData = array_map(function($row) use ($headers) {
return array_combine($headers, $row);
}, array_filter($rows));
$data = [
'page_title' => 'View Campaign',
'campaign' => $campaign,
'campaign_data' => $campaignData
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/campaignView.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
} catch (\Exception $e) {
header('Location: /admin/campaign?error=file_load_failed');
exit;
}
}, 'get');
// Add admin campaign edit routes
Route::add('/admin/campaign/edit/([0-9]+)', function ($id) {
check_login();
$campaignModel = new CampaignModel();
$campaign = $campaignModel->get($id);
if (!$campaign) {
header('Location: /admin/campaign');
exit;
}
$data = [
'page_title' => 'Edit Campaign',
'campaign' => $campaign
];
include_once __DIR__ . '/layout/header/Adminleft_sidebar.php';
include_once __DIR__ . '/campaignEdit.php';
include_once __DIR__ . '/layout/footer/Adminnone_footer.php';
}, 'get');
Route::add('/admin/campaign/edit/([0-9]+)', function ($id) {
check_login();
if (empty($_POST['name']) || empty($_POST['file_id'])) {
header('Location: /admin/campaign/edit/' . $id);
exit;
}
$campaignModel = new CampaignModel();
$campaign = $campaignModel->get($id);
if (!$campaign) {
header('Location: /admin/campaign');
exit;
}
$data = [
'name' => $_POST['name'],
'file_id' => $_POST['file_id']
];
$campaignModel->edit($data, $id);
header('Location: /admin/campaign');
}, 'post');
// Add admin campaign delete route
Route::add('/admin/campaign/delete/([0-9]+)', function ($id) {
check_login();
$campaignModel = new CampaignModel();
$campaignModel->real_delete($id);
header('Location: /admin/campaign');
}, 'get');
// Add admin campaign filter route
Route::add('/admin/campaign/filter', function() {
check_login();
if (!isset($_POST['campaign_id'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing campaign ID']);
exit;
}
$campaignModel = new CampaignModel();
$campaign = $campaignModel->get($_POST['campaign_id']);
if (!$campaign) {
http_response_code(404);
echo json_encode(['error' => 'Campaign not found']);
exit;
}
// Get the current filters
$filters = [
'campaign_name' => $_POST['campaign_name'] ?? null,
'ad_set_name' => $_POST['ad_set_name'] ?? null,
'ad_name' => $_POST['ad_name'] ?? null
];
// Get filtered data
$filteredData = $campaignModel->getFilteredData($campaign, $filters);
echo json_encode([
'data' => $filteredData
]);
}, 'post');
Route::add('/privacy-policy', function () {
include_once __DIR__ . '/privacy-policy.php';
}, 'get');
Route::add('/terms', function () {
include_once __DIR__ . '/terms.php';
}, 'get');
include_once 'client-routes.php';
include_once 'cal.php';
include_once 'oauth-routes.php';
Route::run('/');