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

if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$admin_id = (int)$_SESSION['user_id'];
$payload = json_decode(file_get_contents('php://input'), true);
$property_id = (int)($payload['property_id'] ?? 0);
$action = strtolower(trim((string)($payload['action'] ?? '')));
$admin_notes = trim((string)($payload['admin_notes'] ?? ''));

if ($property_id <= 0 || !in_array($action, ['approve', 'reopen'], true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid property_id or action']);
    exit;
}

function ensureAssignmentWorkflowTable(mysqli $mysqli): void
{
    $mysqli->query("
        CREATE TABLE IF NOT EXISTS property_assignment_workflow (
            id INT AUTO_INCREMENT PRIMARY KEY,
            property_id INT NOT NULL UNIQUE,
            broker_id INT NULL,
            workflow_status VARCHAR(40) NOT NULL DEFAULT 'assigned',
            admin_review_status VARCHAR(20) NOT NULL DEFAULT 'pending',
            broker_confirmed_at DATETIME NULL,
            work_started_at DATETIME NULL,
            work_finished_at DATETIME NULL,
            admin_reviewed_by INT NULL,
            admin_reviewed_at DATETIME NULL,
            admin_notes VARCHAR(255) NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_broker_id (broker_id),
            INDEX idx_workflow_status (workflow_status),
            INDEX idx_admin_review_status (admin_review_status)
        )
    ");
}

try {
    ensureAssignmentWorkflowTable($mysqli);

    $exists = $mysqli->prepare("SELECT property_id FROM property_assignment_workflow WHERE property_id = ? LIMIT 1");
    if (!$exists) {
        throw new Exception($mysqli->error);
    }
    $exists->bind_param('i', $property_id);
    $exists->execute();
    $row = $exists->get_result()->fetch_assoc();
    $exists->close();

    if (!$row) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Assignment workflow not found']);
        exit;
    }

    if ($action === 'approve') {
        $newStatus = 'finished_approved';
        $reviewStatus = 'approved';
        $message = 'Finished work approved';
    } else {
        $newStatus = 'working';
        $reviewStatus = 'rejected';
        $message = 'Finished work rejected and returned to broker';
    }

    $workflowUpdate = $mysqli->prepare("
        UPDATE property_assignment_workflow
        SET workflow_status = ?, admin_review_status = ?, admin_reviewed_by = ?, admin_reviewed_at = NOW(), admin_notes = ?
        WHERE property_id = ?
    ");
    if (!$workflowUpdate) {
        throw new Exception($mysqli->error);
    }
    $workflowUpdate->bind_param('ssisi', $newStatus, $reviewStatus, $admin_id, $admin_notes, $property_id);
    if (!$workflowUpdate->execute()) {
        $workflowUpdate->close();
        throw new Exception('Could not update assignment review');
    }
    $workflowUpdate->close();

    if ($action === 'approve') {
        $propertyUpdate = $mysqli->prepare("UPDATE properties SET status = 'completed' WHERE id = ?");
        if ($propertyUpdate) {
            $propertyUpdate->bind_param('i', $property_id);
            $propertyUpdate->execute();
            $propertyUpdate->close();
        }
    }

    echo json_encode([
        'success' => true,
        'message' => $message,
        'assignment_status' => $newStatus,
        'assignment_review_status' => $reviewStatus
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to review assignment: ' . $e->getMessage()
    ]);
}
?>
