<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class Maintenance extends BaseController
{
    use ResponseTrait;

    protected $secretKey = 'vikas'; // Change this to your secret key

    /**
     * Toggle maintenance mode on/off
     * Usage: GET /maintenance/toggle?key=YOUR_SECRET_KEY&status=off
     * status can be 'on' or 'off'
     */
    public function toggle()
    {
        $key = $this->request->getGet('key');
        $status = $this->request->getGet('status'); // 'on' or 'off'
        $message = $this->request->getGet('message') ?: 'System is under maintenance';

        // Verify secret key
        if ($key !== $this->secretKey) {
            return $this->respond([
                'status' => 'error',
                'message' => 'Invalid authorization key'
            ], 401);
        }

        // Validate status
        if (!in_array($status, ['on', 'off'])) {
            return $this->respond([
                'status' => 'error',
                'message' => 'Status must be "on" or "off"'
            ], 400);
        }

        $db = \Config\Database::connect();
        
        // Update maintenance status
        $sql = "UPDATE system_maintenance SET status = ?, message = ? WHERE id = 1";
        $result = $db->query($sql, [$status, $message]);

        if ($result) {
            return $this->respond([
                'status' => 'success',
                'message' => "Maintenance mode set to: {$status}",
                'maintenance_status' => $status,
                'timestamp' => date('Y-m-d H:i:s')
            ], 200);
        } else {
            return $this->respond([
                'status' => 'error',
                'message' => 'Failed to update maintenance status'
            ], 500);
        }
    }

    /**
     * Check maintenance status
     * Usage: GET /maintenance/status?key=YOUR_SECRET_KEY
     */
    public function status()
    {
        $key = $this->request->getGet('key');

        // Verify secret key
        if ($key !== $this->secretKey) {
            return $this->respond([
                'status' => 'error',
                'message' => 'Invalid authorization key'
            ], 401);
        }

        $db = \Config\Database::connect();
        $query = $db->query("SELECT * FROM system_maintenance WHERE id = 1");
        $result = $query->getRow();

        if ($result) {
            return $this->respond([
                'status' => 'success',
                'maintenance_status' => $result->status,
                'message' => $result->message,
                'updated_at' => $result->updated_at
            ], 200);
        } else {
            return $this->respond([
                'status' => 'error',
                'message' => 'Maintenance record not found'
            ], 404);
        }
    }
}

