<?php
header("Content-Type: application/json");
session_start();
require_once '../config/db.php';

// Security check: Ensure staff is logged in
if (!isset($_SESSION['team_id'])) {
    echo json_encode(["success" => false, "message" => "Unauthorized access."]);
    exit();
}

$id = $_GET['id'] ?? null;
$action = $_GET['action'] ?? null;

if (!$id || !$action) {
    echo json_encode(["success" => false, "message" => "Missing parameters."]);
    exit();
}

try {
    if ($action === 'reject') {
        // Logic for Rejection: Update status to 'Rejected'
        $stmt = $conn->prepare("UPDATE pending_approvals SET status = 'Rejected' WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            echo json_encode(["success" => true, "message" => "Submission has been rejected."]);
        } else {
            throw new Exception($conn->error);
        }
    } 
    
    else if ($action === 'approve') {
        // 1. Fetch details for approval processing
        $res = $conn->query("SELECT * FROM pending_approvals WHERE id = $id");
        $data = $res->fetch_assoc();

        // 2. Perform your business logic here 
        // (e.g., if 'profile_image', update the 'users' table)
        
        // 3. Mark as Approved
        $stmt = $conn->prepare("UPDATE pending_approvals SET status = 'Approved' WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();

        echo json_encode(["success" => true, "message" => "Submission approved successfully."]);
    }

} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "Error: " . $e->getMessage()]);
}