<?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);
$document_id = intval($data['document_id'] ?? 0);
$action = trim($data['action'] ?? '');
$admin_notes = trim($data['admin_notes'] ?? '');

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

try {
    $create_table = "CREATE TABLE IF NOT EXISTS broker_documents (
        id INT AUTO_INCREMENT PRIMARY KEY,
        broker_id INT NOT NULL,
        property_id INT,
        document_name VARCHAR(255) NOT NULL,
        document_type VARCHAR(50),
        file_path VARCHAR(500) NOT NULL,
        file_size INT,
        approval_status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
        admin_notes TEXT,
        uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        approved_at TIMESTAMP NULL,
        FOREIGN KEY(broker_id) REFERENCES users(id),
        FOREIGN KEY(property_id) REFERENCES properties(id)
    )";
    $mysqli->query($create_table);

    $new_status = ($action === 'approve') ? 'approved' : 'rejected';
    $stmt = $mysqli->prepare("
        UPDATE broker_documents
        SET approval_status = ?, admin_notes = ?, approved_at = NOW()
        WHERE id = ? AND approval_status = 'pending'
    ");
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $stmt->bind_param('ssi', $new_status, $admin_notes, $document_id);
    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }
    if ($stmt->affected_rows <= 0) {
        throw new Exception('Document not found or already reviewed');
    }
    $stmt->close();

    echo json_encode([
        'success' => true,
        'message' => $new_status === 'approved' ? 'Document approved successfully' : 'Document rejected successfully'
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

$mysqli->close();
?>
