<?php
/**
 * App API: AC/AAC approve/standby/reject/withdraw signification (same as web officer dashboard POST).
 * POST JSON: user_id (officer), signification_id, action=approve|standby|reject|withdraw, remarks (optional).
 */
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/EmailSender.php';

header('Content-Type: application/json');
// Since request.php contains HTML, we can't just include it. We'll define logActivity here.

function logActivity($pdo, $referenceType, $referenceId, $description, $status, $performedByRole, $performedByUserId = null, $performedByAdminId = null) {
    $stmt = $pdo->prepare("
        INSERT INTO activity_logs (reference_type, reference_id, description, status, performed_by_role, performed_by_user_id, performed_by_admin_id) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$referenceType, $referenceId, $description, $status, $performedByRole, $performedByUserId, $performedByAdminId]);
}

$response = ['success' => false, 'message' => ''];

try {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $officerUserId = isset($input['user_id']) ? (int) $input['user_id'] : 0;
    $significationId = isset($input['signification_id']) ? (int) $input['signification_id'] : 0;
    $action = trim(strtolower($input['action'] ?? ''));
    $remarks = trim($input['remarks'] ?? '');

    if ($officerUserId <= 0 || $significationId <= 0 || !in_array($action, ['approve', 'standby', 'reject', 'withdraw', 'reject_withdrawal'])) {
        $response['message'] = 'Missing or invalid user_id, signification_id, or action';
        echo json_encode($response);
        exit;
    }

    $stmt = $pdo->prepare("SELECT id, role, area FROM users WHERE id = ? AND status = 'approved'");
    $stmt->execute([$officerUserId]);
    $officer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$officer || !in_array($officer['role'], ['AC', 'AAC'])) {
        $response['message'] = 'Unauthorized. AC or AAC only.';
        echo json_encode($response);
        exit;
    }

    $officerArea = trim($officer['area'] ?? '');
    $role = $officer['role'];

    // Get signification and ensure member is in officer's area
    $stmt = $pdo->prepare("
        SELECT ms.id, ms.match_id, ms.user_id, ms.previous_status, u.email, u.first_name, u.last_name, u.area, u.nroi_id, m.match_name
        FROM match_significations ms
        JOIN users u ON ms.user_id = u.id
        JOIN match_schedules m ON ms.match_id = m.id
        WHERE ms.id = ? AND TRIM(COALESCE(u.area, '')) = ?
    ");
    $stmt->execute([$significationId, $officerArea]);
    $sig = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sig) {
        $response['message'] = 'Signification not found or not in your area.';
        echo json_encode($response);
        exit;
    }

    $status = '';
    $notifStatus = '';
    $prevStatusVal = $sig['previous_status'] ?? 'approved';

    if ($action === 'approve') {
        $status = 'approved';
        $notifStatus = 'Approved';
    } elseif ($action === 'reject') {
        $status = 'declined';
        $notifStatus = 'Declined';
    } elseif ($action === 'standby') {
        $status = 'standby';
        $notifStatus = 'Standby';
    } elseif ($action === 'reject_withdrawal') {
        $status = $prevStatusVal;
        $notifStatus = 'Withdrawal Rejected';
    } else {
        $status = 'withdrawn';
        $notifStatus = 'Withdrawn';
        if ($remarks === '') {
            $remarks = 'Directly withdrawn by officer';
        }
    }

    $stmt = $pdo->prepare("UPDATE match_significations SET status = ?, officer_remarks = ?, reviewed_by = ?, reviewed_at = NOW() WHERE id = ?");
    $stmt->execute([$status, $remarks, $officerUserId, $significationId]);

    // Fetch match details for email
    $stmtM = $pdo->prepare("SELECT match_name, start_date, end_date, location FROM match_schedules WHERE id = ?");
    $stmtM->execute([$sig['match_id']]);
    $match = $stmtM->fetch(PDO::FETCH_ASSOC);

    if ($match && !empty($sig['email'])) {
        $fullName = trim(($sig['first_name'] ?? '') . ' ' . ($sig['last_name'] ?? ''));
        $sDate = strtotime($match['start_date']);
        $eDate = strtotime($match['end_date']);
        $schedule = (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
            ? date('M d, Y', $sDate)
            : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);
        
        $emailReason = in_array($action, ['withdraw', 'reject', 'reject_withdrawal']) ? $remarks : '';
        sendMatchNotification($sig['email'], $fullName, $notifStatus, $match['match_name'], $schedule, $match['location'], $emailReason, $role, 0, null, $prevStatusVal);
    }

    // Log the activity so it shows up on the web portal timestamp
    $stmtName = $pdo->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
    $stmtName->execute([$officerUserId]);
    $u = $stmtName->fetch(PDO::FETCH_ASSOC);
    $performerName = $u ? trim($u['first_name'] . ' ' . $u['last_name']) : 'Officer';

    $actionVerb = ($action === 'approve') ? 'Approved' : (($action === 'standby') ? 'Standby' : (($action === 'reject') ? 'Rejected' : 'Withdrawn'));
    $logDesc = "$actionVerb by $performerName ($role)";
    
    logActivity($pdo, 'match_signification', $significationId, $logDesc, $status, $role, $officerUserId);

    $response['success'] = true;
    $response['message'] = 'Signification ' . ucfirst($status) . ' successfully.';
} catch (Throwable $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
