<?php
session_start();

// Suppress PHP warnings/notices so AJAX always receives clean JSON
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', 0);

header('Content-Type: application/json');

if (!isset($_SESSION["purchase_code"])) {
        echo json_encode(['st' => 0, 'msg' => 'Invalid purchase code!']);
        exit;
}

$db_config_path = 'application/config/database.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST)) {
        require_once 'includes/taskCoreClass.php';
        require_once 'includes/databaseLibrary.php';

        $core     = new Core();
        $database = new Database();

        // ✅ Validate required fields
        if (!$core->checkEmpty($_POST)) {
                echo json_encode([
                        'st'  => 0,
                        'msg' => 'The host, username, password, database name, and other information are required.'
                ]);
                exit;
        }

        // ✅ Check DB connection
        $checkDB = $database->check_database($_POST);
        if ($checkDB['st'] == 0) {
                echo json_encode($checkDB);
                exit;
        }

        // ✅ Run installation (includes API call and DB writes)
        $install = $database->install($_POST);
        if ($install['st'] == 0) {
                echo json_encode($install);
                exit;
        }

        // ✅ Check config file
        if ($core->checkFile() == 0) {
                echo json_encode([
                        'st'  => 0,
                        'msg' => "File {$db_config_path} is empty"
                ]);
                exit;
        }

        // ✅ Write config (only after successful install)
        if ($core->write_db_config($_POST) === false) {
                echo json_encode([
                        'st'  => 0,
                        'msg' => "The database configuration file could not be written. Please chmod {$db_config_path} to 777"
                ]);
                exit;
        }

        // ✅ Success
        echo json_encode(['st' => 1, 'msg' => 'Installation successful']);
        exit;
} else {
        echo json_encode(['st' => 0, 'msg' => 'Invalid request']);
        exit;
}
