37497-vm/approve_request.php
Flatlogic Bot 65bff23a0b 1
2026-01-16 09:31:10 +00:00

93 lines
2.9 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['request_id']) || !isset($_POST['action'])) {
header('Location: request_dashboard.php?error=invalid_request');
exit;
}
$request_id = $_POST['request_id'];
$action = $_POST['action'];
try {
$pdo = db();
// Get the request details
$stmt = $pdo->prepare('SELECT * FROM ChangeRequests WHERE id = ?');
$stmt->execute([$request_id]);
$request = $stmt->fetch();
if (!$request) {
header('Location: request_dashboard.php?error=not_found');
exit;
}
// Authorization check
$is_authorized = false;
if (isset($_SESSION['role'])) {
$user_role = $_SESSION['role'];
$user_department = $_SESSION['department'] ?? null;
$request_status = $request['status'];
$pending_level = $request['approval_level_pending'];
$request_department = $request['department_name'];
if ($request_status === 'Pending Approval' && $user_role === $pending_level) {
if ($user_role === 'Admin' || $user_department === $request_department) {
$is_authorized = true;
}
}
}
if (!$is_authorized) {
header('Location: request_dashboard.php?error=unauthorized');
exit;
}
$next_approval_level = '';
$new_status = '';
$rejection_reason = null;
if ($action === 'approve') {
$current_level = $request['approval_level_pending'];
$approval_flow = ['Dept Manager/GM', 'System Div Admin', 'Planning Dept', 'System GM'];
$current_index = array_search($current_level, $approval_flow);
if ($current_index !== false && $current_index < count($approval_flow) - 1) {
$next_approval_level = $approval_flow[$current_index + 1];
$new_status = 'Pending Approval';
} else {
$next_approval_level = 'None';
$new_status = 'Approved';
}
$sql = 'UPDATE ChangeRequests SET status = ?, approval_level_pending = ? WHERE id = ?';
$params = [$new_status, $next_approval_level, $request_id];
} elseif ($action === 'reject') {
$next_approval_level = $request['approval_level_pending'];
$new_status = 'Rejected';
$rejection_reason = $_POST['rejection_reason'] ?? '';
$sql = 'UPDATE ChangeRequests SET status = ?, approval_level_pending = ?, rejection_reason = ? WHERE id = ?';
$params = [$new_status, $next_approval_level, $rejection_reason, $request_id];
}
if (isset($sql)) {
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
}
header('Location: request_dashboard.php?success=updated');
exit;
} catch (PDOException $e) {
header('Location: request_dashboard.php?error=db_error');
exit;
}