<?php
session_start();
header('Content-Type: application/json');

if (file_exists(__DIR__ . '/installed.lock')) {
    echo json_encode(['success' => false, 'message' => 'Installation already completed.']);
    exit;
}

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

$siteName = isset($_POST['site_name']) ? trim($_POST['site_name']) : '';
$siteUrl = isset($_POST['site_url']) ? trim($_POST['site_url']) : '';
$contactPhone = isset($_POST['contact_phone']) ? trim($_POST['contact_phone']) : '';
$contactEmail = isset($_POST['contact_email']) ? trim($_POST['contact_email']) : '';

if (empty($siteName)) {
    echo json_encode(['success' => false, 'message' => 'Site name is required.']);
    exit;
}

if (empty($_SESSION['install_db'])) {
    echo json_encode(['success' => false, 'message' => 'Database configuration not found.']);
    exit;
}

$dbConfig = $_SESSION['install_db'];

try {
    $dsn = "mysql:host={$dbConfig['host']};port={$dbConfig['port']};dbname={$dbConfig['dbname']};charset=utf8mb4";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password'], [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]);

    $upsertSettings = $pdo->prepare("
        INSERT INTO system_settings (setting_key, setting_value, setting_type, group_name, created_at, updated_at)
        VALUES (?, ?, 'text', 'general', NOW(), NOW())
        ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()
    ");

    $upsertSettings->execute(['platform_name', $siteName]);
    $upsertSettings->execute(['platform_url', $siteUrl]);

    $upsertWebsite = $pdo->prepare("
        INSERT INTO website_settings (setting_key, setting_value, setting_type, group_name, created_at, updated_at)
        VALUES (?, ?, 'text', 'general', NOW(), NOW())
        ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()
    ");

    $upsertWebsite->execute(['site_name', $siteName]);

    if (!empty($contactPhone)) {
        $upsertWebsite->execute(['contact_phone', $contactPhone]);
        $upsertSettings->execute(['admin_email', $contactEmail]);
    }
    if (!empty($contactEmail)) {
        $upsertWebsite->execute(['contact_email', $contactEmail]);
    }

    // Handle logo upload
    $logoUrl = '';
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = dirname(__DIR__) . '/uploads/logo/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileTmp = $_FILES['logo']['tmp_name'];
        $fileName = $_FILES['logo']['name'];
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

        if (in_array($fileExt, $allowedExts)) {
            $newFileName = 'site_logo_' . time() . '.' . $fileExt;
            $destPath = $uploadDir . $newFileName;

            if (move_uploaded_file($fileTmp, $destPath)) {
                $logoUrl = 'uploads/logo/' . $newFileName;
                $upsertWebsite->execute(['site_logo', $logoUrl]);
            }
        }
    }

    // Create installed.lock
    $lockContent = "Tap2Order Installation Complete\n";
    $lockContent .= "Date: " . date('Y-m-d H:i:s') . "\n";
    $lockContent .= "IP: " . ($_SERVER['REMOTE_ADDR'] ?? '127.0.0.1') . "\n";
    $lockContent .= "Version: 1.0.0\n";
    file_put_contents(__DIR__ . '/installed.lock', $lockContent);

    $_SESSION['install_site'] = ['site_name' => $siteName, 'site_url' => $siteUrl];

    echo json_encode(['success' => true, 'message' => 'Site configuration saved successfully.']);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
