<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in and has approval rights
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user role
$user_id = $_SESSION['user_id'];
$role_query = "SELECT role_id FROM users WHERE user_id = ?";
$stmt = $conn->prepare($role_query);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

// Check if user has approval rights
if (!in_array($user['role_id'], [1, 2, 3])) { // Admin, General Manager, Operations
    $_SESSION['error_message'] = "You don't have permission to reject expenses.";
    header('Location: expense_list.php');
    exit();
}

// Check if expense ID and reason are provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = "Invalid expense ID.";
    header('Location: expense_list.php');
    exit();
}

$expense_id = intval($_GET['id']);
$rejection_reason = $_POST['rejection_reason'] ?? '';

try {
    // Start transaction
    $conn->begin_transaction();

    // Get expense details
    $expense_query = "SELECT * FROM expenses WHERE id = ? AND status = 'Pending'";
    $stmt = $conn->prepare($expense_query);
    $stmt->bind_param('i', $expense_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception("Expense not found or already processed.");
    }

    $expense = $result->fetch_assoc();

    // Update expense status
    $update_query = "UPDATE expenses SET 
                    status = 'Rejected',
                    description = CONCAT(description, ' | Rejection reason: ', ?),
                    WHERE id = ?";
    
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param('sii', $rejection_reason, $user_id, $expense_id);
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to update expense status.");
    }

    // Create notification
    $notif_message = "Expense {$expense['exp_no']} has been rejected. Reason: " . ($rejection_reason ?: 'No reason provided');
    $notif_query = "INSERT INTO notifications (
                        user_id,
                        notif_message,
                        created_at
                    ) VALUES (?, ?, NOW())";
    
    $stmt = $conn->prepare($notif_query);
    $stmt->bind_param('is', $expense['user_id'], $notif_message);
    $stmt->execute();

    // Commit transaction
    $conn->commit();

    $_SESSION['success_message'] = "Expense {$expense['exp_no']} has been rejected.";
    header('Location: expense_list.php');
    exit();

} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header('Location: expense_list.php');
    exit();
}
?>