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

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

$data = json_decode(file_get_contents('php://input'), true);
$request_id = intval($data['request_id'] ?? 0);
$action = trim($data['action'] ?? '');
$admin_price = isset($data['admin_price']) ? floatval($data['admin_price']) : 0;
$admin_notes = trim($data['admin_notes'] ?? '');

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

function resolvePropertyBrokerId(mysqli $mysqli, int $requestedBrokerId): ?int
{
    if ($requestedBrokerId <= 0) {
        return null;
    }

    $fkRefTable = null;
    $fkQuery = "
        SELECT REFERENCED_TABLE_NAME
        FROM information_schema.KEY_COLUMN_USAGE
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 'properties'
          AND COLUMN_NAME = 'broker_id'
          AND REFERENCED_TABLE_NAME IS NOT NULL
        LIMIT 1
    ";
    if ($res = $mysqli->query($fkQuery)) {
        if ($row = $res->fetch_assoc()) {
            $fkRefTable = strtolower((string)($row['REFERENCED_TABLE_NAME'] ?? ''));
        }
        $res->free();
    }

    if ($fkRefTable === 'brokers') {
        $chk = $mysqli->prepare("SELECT id FROM brokers WHERE id = ? LIMIT 1");
        if ($chk) {
            $chk->bind_param('i', $requestedBrokerId);
            $chk->execute();
            $ok = $chk->get_result()->fetch_assoc();
            $chk->close();
            if ($ok) {
                return $requestedBrokerId;
            }
        }

        // Try mapping users.id -> brokers.id by email when mixed schema is used
        $userEmail = null;
        $u = $mysqli->prepare("SELECT email FROM users WHERE id = ? LIMIT 1");
        if ($u) {
            $u->bind_param('i', $requestedBrokerId);
            $u->execute();
            $uRow = $u->get_result()->fetch_assoc();
            $u->close();
            $userEmail = $uRow['email'] ?? null;
        }
        if (!empty($userEmail)) {
            $b = $mysqli->prepare("SELECT id FROM brokers WHERE email = ? LIMIT 1");
            if ($b) {
                $b->bind_param('s', $userEmail);
                $b->execute();
                $bRow = $b->get_result()->fetch_assoc();
                $b->close();
                if (!empty($bRow['id'])) {
                    return intval($bRow['id']);
                }
            }
        }
        return null;
    }

    // Default/current schema: properties.broker_id -> users.id
    $chk = $mysqli->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
    if ($chk) {
        $chk->bind_param('i', $requestedBrokerId);
        $chk->execute();
        $ok = $chk->get_result()->fetch_assoc();
        $chk->close();
        if ($ok) {
            return $requestedBrokerId;
        }
    }

    return null;
}

try {
    $mysqli->begin_transaction();

    $mysqli->query("
        CREATE TABLE IF NOT EXISTS property_approval_requests (
            id INT AUTO_INCREMENT PRIMARY KEY,
            property_id INT NULL,
            broker_id INT NOT NULL,
            request_type VARCHAR(30) NOT NULL DEFAULT 'update',
            title VARCHAR(255) NULL,
            description TEXT NULL,
            price DECIMAL(12,2) NULL,
            type VARCHAR(50) NULL,
            address VARCHAR(255) NULL,
            city VARCHAR(100) NULL,
            state VARCHAR(100) NULL,
            bedrooms INT NULL,
            bathrooms INT NULL,
            image_url VARCHAR(500) NULL,
            approval_status VARCHAR(20) NOT NULL DEFAULT 'pending',
            admin_price DECIMAL(12,2) NULL,
            admin_notes TEXT NULL,
            reviewed_by INT NULL,
            reviewed_at TIMESTAMP NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    ");

    $stmt = $mysqli->prepare("SELECT * FROM property_approval_requests WHERE id = ? AND approval_status = 'pending' LIMIT 1");
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $stmt->bind_param('i', $request_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $request = $result->fetch_assoc();
    $stmt->close();

    if (!$request) {
        throw new Exception('Pending request not found');
    }

    $resolvedBrokerId = resolvePropertyBrokerId($mysqli, intval($request['broker_id']));
    $final_broker_id = $resolvedBrokerId ?? 0;
    $final_price = $admin_price > 0 ? $admin_price : floatval($request['price'] ?? 0);
    $admin_id = intval($_SESSION['user_id']);
    $property_id = intval($request['property_id'] ?? 0);

    if ($action === 'approve') {
        if ($admin_price <= 0) {
            throw new Exception('Admin price is required for approval');
        }
        if ($property_id > 0 && $request['request_type'] === 'update') {
            $upd = $mysqli->prepare("
                UPDATE properties SET
                    title = COALESCE(NULLIF(?, ''), title),
                    description = COALESCE(NULLIF(?, ''), description),
                    price = CASE WHEN ? > 0 THEN ? ELSE price END,
                    type = COALESCE(NULLIF(?, ''), type),
                    address = COALESCE(NULLIF(?, ''), address),
                    city = COALESCE(NULLIF(?, ''), city),
                    state = COALESCE(NULLIF(?, ''), state),
                    bedrooms = COALESCE(?, bedrooms),
                    bathrooms = COALESCE(?, bathrooms),
                    image_url = COALESCE(NULLIF(?, ''), image_url),
                    broker_id = CASE WHEN ? > 0 THEN ? ELSE broker_id END,
                    status = 'active',
                    updated_at = NOW()
                WHERE id = ?
            ");
            if (!$upd) {
                throw new Exception('Prepare failed: ' . $mysqli->error);
            }
            $bedrooms = isset($request['bedrooms']) ? intval($request['bedrooms']) : null;
            $bathrooms = isset($request['bathrooms']) ? intval($request['bathrooms']) : null;
            $upd->bind_param(
                'ssddssssiisiii',
                $request['title'],
                $request['description'],
                $final_price,
                $final_price,
                $request['type'],
                $request['address'],
                $request['city'],
                $request['state'],
                $bedrooms,
                $bathrooms,
                $request['image_url'],
                $final_broker_id,
                $final_broker_id,
                $property_id
            );
            if (!$upd->execute()) {
                throw new Exception('Property update failed: ' . $upd->error);
            }
            $upd->close();
        } else {
            $ins = $mysqli->prepare("
                INSERT INTO properties
                (title, description, price, type, status, address, city, state, bedrooms, bathrooms, image_url, broker_id)
                VALUES (?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, NULLIF(?, 0))
            ");
            if (!$ins) {
                throw new Exception('Prepare failed: ' . $mysqli->error);
            }
            $bedrooms = isset($request['bedrooms']) ? intval($request['bedrooms']) : 0;
            $bathrooms = isset($request['bathrooms']) ? intval($request['bathrooms']) : 0;
            $ins->bind_param(
                'ssdssssiisi',
                $request['title'],
                $request['description'],
                $final_price,
                $request['type'],
                $request['address'],
                $request['city'],
                $request['state'],
                $bedrooms,
                $bathrooms,
                $request['image_url'],
                $final_broker_id
            );
            if (!$ins->execute()) {
                throw new Exception('Property insert failed: ' . $ins->error);
            }
            $property_id = $ins->insert_id;
            $ins->close();
        }
    }

    $new_status = ($action === 'approve') ? 'approved' : 'rejected';
    if ($admin_notes === '') {
        $admin_notes = $action === 'approve'
            ? 'Approved by admin with final price: ' . number_format((float)$final_price, 2)
            : 'Rejected by admin';
    }

    $req_upd = $mysqli->prepare("
        UPDATE property_approval_requests
        SET approval_status = ?, admin_price = ?, admin_notes = ?, reviewed_by = ?, reviewed_at = NOW(), property_id = ?
        WHERE id = ?
    ");
    if (!$req_upd) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $req_upd->bind_param('sdsiii', $new_status, $final_price, $admin_notes, $admin_id, $property_id, $request_id);
    if (!$req_upd->execute()) {
        throw new Exception('Request update failed: ' . $req_upd->error);
    }
    $req_upd->close();

    $mysqli->commit();

    echo json_encode([
        'success' => true,
        'message' => $action === 'approve' ? 'Listing approved and applied' : 'Listing rejected',
        'property_id' => $property_id
    ]);
} catch (Exception $e) {
    $mysqli->rollback();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

$mysqli->close();
?>
