<?php
declare(strict_types=1);

require_once '../config/database.php';
require_once '../app/helpers/rbac.php';
require_once '../app/helpers/notification.php';
require_once '../app/helpers/audit.php';
require_once '../app/helpers/api_security.php';

header('Content-Type: application/json');

requireApiLogin();
enforceCsrfForUnsafeRequest();

if (!can('workflow.approve')) {
    echo json_encode(['status'=>'error','message'=>'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? '';
$step_id = isset($_POST['step_id']) ? (int)$_POST['step_id'] : 0;
$user_id = $_SESSION['user_id'] ?? 0;

if ($step_id <= 0) {
    echo json_encode(['status'=>'error','message'=>'Invalid step']);
    exit;
}

try {

switch ($action) {

case 'approve':

    // 1. Approve step
    $stmt = $pdo->prepare("
        UPDATE workflow_steps
        SET status='Approved', action_by=?, action_at=NOW()
        WHERE id=?
    ");
    $stmt->execute([$user_id, $step_id]);

    // 2. Get workflow_id
    $stmt = $pdo->prepare("SELECT workflow_id FROM workflow_steps WHERE id=? AND deleted_at IS NULL");
    $stmt->execute([$step_id]);
    $workflow_id = (int)$stmt->fetchColumn();

    if (!$workflow_id) {
        echo json_encode(['status'=>'error','message'=>'Workflow not found']);
        exit;
    }

    // 3. Get creator
    $stmt = $pdo->prepare("SELECT created_by FROM workflows WHERE id=? AND deleted_at IS NULL");
    $stmt->execute([$workflow_id]);
    $creator_id = (int)$stmt->fetchColumn();

    // 4. Check pending steps
    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM workflow_steps
        WHERE workflow_id=? AND status='Pending' AND deleted_at IS NULL
    ");
    $stmt->execute([$workflow_id]);
    $pending = (int)$stmt->fetchColumn();

    // 5. Update workflow status
    if ($pending === 0) {
        $pdo->prepare("UPDATE workflows SET status='Approved' WHERE id=?")
            ->execute([$workflow_id]);

        // Notification (final)
        notify($pdo, $creator_id,
            'Request Fully Approved',
            'Your request has been fully approved',
            'workflow',
            'workflow_view.php?id='.$workflow_id,
            $workflow_id
        );

        // Audit
        audit($pdo, $user_id, 'approve', 'workflow', $workflow_id,
            'Workflow fully approved',
            ['status'=>'Pending'],
            ['status'=>'Approved']
        );

    } else {

        // Notification (step progress)
        notify($pdo, $creator_id,
            'Approval Progress',
            'Your request has passed one approval stage',
            'workflow',
            'workflow_view.php?id='.$workflow_id,
            $workflow_id
        );
    }

    echo json_encode(['status'=>'success']);
    break;


case 'reject':

    // 1. Reject step
    $pdo->prepare("
        UPDATE workflow_steps
        SET status='Rejected', action_by=?, action_at=NOW()
        WHERE id=?
    ")->execute([$user_id, $step_id]);

    // 2. Get workflow
    $stmt = $pdo->prepare("SELECT workflow_id FROM workflow_steps WHERE id=? AND deleted_at IS NULL");
    $stmt->execute([$step_id]);
    $workflow_id = (int)$stmt->fetchColumn();

    // 3. Reject workflow
    $pdo->prepare("UPDATE workflows SET status='Rejected' WHERE id=?")
        ->execute([$workflow_id]);

    // 4. Get creator
    $stmt = $pdo->prepare("SELECT created_by FROM workflows WHERE id=? AND deleted_at IS NULL");
    $stmt->execute([$workflow_id]);
    $creator_id = (int)$stmt->fetchColumn();

    // Notification
    notify($pdo, $creator_id,
        'Request Rejected',
        'Your request has been rejected',
        'workflow',
        'workflow_view.php?id='.$workflow_id,
        $workflow_id
    );

    // Audit
    audit($pdo, $user_id, 'reject', 'workflow', $workflow_id,
        'Workflow rejected',
        ['status'=>'Pending'],
        ['status'=>'Rejected']
    );

    echo json_encode(['status'=>'success']);
    break;


default:
    echo json_encode(['status'=>'error','message'=>'Invalid action']);
}

} catch (Throwable $e) {
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
