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

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

$session_broker_id = (int)$_SESSION['user_id'];
$brokerCtx = resolveBrokerContext($mysqli, $session_broker_id);
$broker_id = (int)$brokerCtx['property_broker_id'];
$fallback_broker_id = $session_broker_id !== $broker_id ? $session_broker_id : 0;
$payload = json_decode(file_get_contents('php://input'), true);
$property_id = (int)($payload['property_id'] ?? 0);
$action = strtolower(trim((string)($payload['action'] ?? '')));

if ($property_id <= 0 || !in_array($action, ['confirm', 'finish'], 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);

    $ownership = $mysqli->prepare("
        SELECT id
        FROM properties
        WHERE id = ?
          AND (broker_id = ? OR (? > 0 AND broker_id = ?))
        LIMIT 1
    ");
    if (!$ownership) {
        throw new Exception($mysqli->error);
    }
    $ownership->bind_param('iiii', $property_id, $broker_id, $fallback_broker_id, $fallback_broker_id);
    $ownership->execute();
    $owned = $ownership->get_result()->fetch_assoc();
    $ownership->close();
    if (!$owned) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Property is not assigned to your account']);
        exit;
    }

    if ($action === 'confirm') {
        $stmt = $mysqli->prepare("
            INSERT INTO property_assignment_workflow (
                property_id, broker_id, workflow_status, admin_review_status,
                broker_confirmed_at, work_started_at, work_finished_at,
                admin_reviewed_by, admin_reviewed_at, admin_notes
            )
            VALUES (?, ?, 'working', 'pending', NOW(), NOW(), NULL, NULL, NULL, NULL)
            ON DUPLICATE KEY UPDATE
                broker_id = VALUES(broker_id),
                workflow_status = 'working',
                admin_review_status = 'pending',
                broker_confirmed_at = COALESCE(broker_confirmed_at, NOW()),
                work_started_at = COALESCE(work_started_at, NOW()),
                work_finished_at = NULL,
                admin_reviewed_by = NULL,
                admin_reviewed_at = NULL,
                admin_notes = NULL
        ");
        if (!$stmt) {
            throw new Exception($mysqli->error);
        }
        $stmt->bind_param('ii', $property_id, $broker_id);
        if (!$stmt->execute()) {
            $stmt->close();
            throw new Exception('Could not confirm assignment');
        }
        $stmt->close();

        echo json_encode([
            'success' => true,
            'message' => 'Work confirmed and marked as working',
            'assignment_status' => 'working'
        ]);
        exit;
    }

    $stmt = $mysqli->prepare("
        INSERT INTO property_assignment_workflow (
            property_id, broker_id, workflow_status, admin_review_status,
            broker_confirmed_at, work_started_at, work_finished_at,
            admin_reviewed_by, admin_reviewed_at, admin_notes
        )
        VALUES (?, ?, 'finished_pending_admin', 'pending', NOW(), NOW(), NOW(), NULL, NULL, NULL)
        ON DUPLICATE KEY UPDATE
            broker_id = VALUES(broker_id),
            workflow_status = 'finished_pending_admin',
            admin_review_status = 'pending',
            broker_confirmed_at = COALESCE(broker_confirmed_at, NOW()),
            work_started_at = COALESCE(work_started_at, NOW()),
            work_finished_at = NOW(),
            admin_reviewed_by = NULL,
            admin_reviewed_at = NULL,
            admin_notes = NULL
    ");
    if (!$stmt) {
        throw new Exception($mysqli->error);
    }
    $stmt->bind_param('ii', $property_id, $broker_id);
    if (!$stmt->execute()) {
        $stmt->close();
        throw new Exception('Could not submit work completion');
    }
    $stmt->close();

    echo json_encode([
        'success' => true,
        'message' => 'Work marked finished and sent to admin for review',
        'assignment_status' => 'finished_pending_admin'
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to update assignment status: ' . $e->getMessage()
    ]);
}
?>
