<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    $_SESSION['sweet_alert'] = [
        'title' => 'Access Denied',
        'text' => "You don't have permission to perform this action",
        'icon' => 'error'
    ];
    header('Location: all_expenses.php');
    exit();
}

// Check if ID and status parameters exist
if (!isset($_GET['id']) || empty($_GET['id']) || !isset($_GET['status']) || empty($_GET['status'])) {
    $_SESSION['sweet_alert'] = [
        'title' => 'Error!',
        'text' => "Missing parameters",
        'icon' => 'error'
    ];
    header('Location: all_expenses.php');
    exit();
}

$expense_id = intval($_GET['id']);
$status = $_GET['status'];
$reason = isset($_GET['reason']) ? $_GET['reason'] : '';

// Validate status
if (!in_array($status, ['Approved', 'Rejected', 'Pending'])) {
    $_SESSION['sweet_alert'] = [
        'title' => 'Error!',
        'text' => "Invalid status value",
        'icon' => 'error'
    ];
    header('Location: all_expenses.php');
    exit();
}

try {
    // Get the current expense info
    $select_stmt = $conn->prepare("SELECT exp_no FROM expenses WHERE id = ?");
    $select_stmt->bind_param("i", $expense_id);
    $select_stmt->execute();
    $result = $select_stmt->get_result();
    
    if ($result->num_rows === 0) {
        $_SESSION['sweet_alert'] = [
            'title' => 'Error!',
            'text' => "Expense not found",
            'icon' => 'error'
        ];
        header('Location: all_expenses.php');
        exit();
    }
    
    $expense = $result->fetch_assoc();
    $exp_no = $expense['exp_no'];
    $select_stmt->close();
    
    // Update the expense status
    $stmt = $conn->prepare("UPDATE expenses SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $status, $expense_id);
    
    if ($stmt->execute()) {
        // If rejection includes a reason, update the description
        if ($status === 'Rejected' && !empty($reason)) {
            $updateDesc = $conn->prepare("UPDATE expenses SET description = CONCAT(description, ' | Rejection reason: ', ?) WHERE id = ?");
            $updateDesc->bind_param("si", $reason, $expense_id);
            $updateDesc->execute();
            $updateDesc->close();
        }
        
        // Log the status change in audit log (if you have one)
        // logAuditAction('expense_status_change', 'Changed expense status for ID: ' . $expense_id . ' to ' . $status, null, null);
        
        $_SESSION['sweet_alert'] = [
            'title' => 'Success!',
            'text' => "Expense $exp_no has been " . strtolower($status) . " successfully.",
            'icon' => 'success'
        ];
    } else {
        $_SESSION['sweet_alert'] = [
            'title' => 'Error!',
            'text' => "Failed to update expense status: " . $stmt->error,
            'icon' => 'error'
        ];
    }
    
    $stmt->close();
} catch (Exception $e) {
    $_SESSION['sweet_alert'] = [
        'title' => 'Error!',
        'text' => "An exception occurred: " . $e->getMessage(),
        'icon' => 'error'
    ];
}

// Redirect back to expense list
header('Location: all_expenses.php');
exit();
?>