<?php
require_once '../../includes/auth.php';
require_once '../../config/database.php';
require_once '../../config/logger.php';
require_once '../../includes/sms_functions.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

if (!hasRole(['admin','diocesan_chairman','diocese_chairman','diocesan_secretary','diocesan_treasurer','diocesan_dom','diocesan_music_director'])) {
    echo json_encode(['success' => false, 'message' => 'No permission']);
    exit;
}

$adId = isset($_POST['ad_id']) ? (int)$_POST['ad_id'] : 0;
$action = isset($_POST['action']) ? trim($_POST['action']) : '';
if ($adId <= 0 || !in_array($action, ['approve','reject'], true)) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

$ad = fetchRow("SELECT * FROM ads WHERE id = ?", [$adId]);
if (!$ad) {
    echo json_encode(['success' => false, 'message' => 'Ad not found']);
    exit;
}

if ($ad['status'] !== 'pending' || $ad['workflow_state'] !== 'pending_approval') {
    echo json_encode(['success' => false, 'message' => 'Ad is not awaiting approval']);
    exit;
}

if (!in_array($ad['payment_status'], ['paid','waived'], true)) {
    echo json_encode(['success' => false, 'message' => 'Payment not completed']);
    exit;
}

// Load creator info (tolerate missing role row)
$creator = fetchRow("SELECT u.id, u.diocese_id, r.role_key FROM users u LEFT JOIN roles r ON u.role_id = r.id WHERE u.id = ?", [ (int)$ad['created_by'] ]);
$creator_id = $creator['id'] ?? 0;
$creator_role_key = $creator['role_key'] ?? '';
$creator_diocese_id = isset($creator['diocese_id']) ? (int)$creator['diocese_id'] : 0;

$currentUserId = $_SESSION['user_id'];
if ($currentUserId == $creator_id) {
    echo json_encode(['success' => false, 'message' => 'You cannot approve your own advert']);
    exit;
}

// Determine approver info
$approverRow = fetchRow("SELECT u.id, u.diocese_id, r.role_key FROM users u LEFT JOIN roles r ON u.role_id = r.id WHERE u.id = ?", [$currentUserId]);
$approver_role_key = $approverRow['role_key'] ?? '';
$approver_diocese_id = isset($approverRow['diocese_id']) ? (int)$approverRow['diocese_id'] : 0;

$creatorIsConnex = in_array($creator_role_key, ['admin'], true);
$creatorIsDiocese = !$creatorIsConnex;
$approverIsConnex = in_array($approver_role_key, ['admin'], true);
$approverIsDiocese = !$approverIsConnex;

// Approval rules
if ($creatorIsDiocese) {
    if (!($approverIsConnex || ($approverIsDiocese && $approver_diocese_id > 0 && $approver_diocese_id === $creator_diocese_id))) {
        echo json_encode(['success' => false, 'message' => 'Only same-diocese diocese roles or connexion roles can approve this advert']);
        exit;
    }
} else {
    if (!$approverIsConnex) {
        echo json_encode(['success' => false, 'message' => 'Only connexion roles can approve this advert']);
        exit;
    }
}

$status = $action === 'approve' ? 'approved' : 'rejected';
$wf = $action === 'approve' ? 'approved' : 'rejected';
$ok = executeQuery("UPDATE ads SET status=?, workflow_state=?, approved_by=?, approved_at=NOW() WHERE id=?", [$status, $wf, $currentUserId, $adId]);

if ($ok) {
    $tbl = fetchRow("SHOW TABLES LIKE 'ad_approval_history'");
    if ($tbl) {
        executeQuery("INSERT INTO ad_approval_history (ad_id, action, note, by_user_id) VALUES (?,?,?,?)", [(int)$adId, $status, null, (int)$currentUserId]);
    }
    $recipient = '';
    if (!empty($ad['contact_phone'])) { $recipient = $ad['contact_phone']; }
    if ($recipient !== '') {
        $msg = "Your advert '" . $ad['title'] . "' has been " . ($status === 'approved' ? 'approved' : 'rejected') . ".";
        try { sendSMS($recipient, $msg); } catch (Exception $e) {}
    }
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
