<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Setting;
use App\Models\AuditLog;

class SettingController extends Controller
{
    public function index()
    {
        $settings = Setting::pluck('value', 'key');
        return response()->json(['success' => true, 'data' => $settings]);
    }

    public function update(Request $request)
    {
        $data = $request->except(['_token']);
        foreach ($data as $key => $val) {
            Setting::updateOrCreate(['key' => $key], ['value' => (string)$val]);
        }

        AuditLog::create([
            'user_id' => $request->user()?->id,
            'user_name' => $request->user()?->name,
            'action' => 'UPDATE_SETTINGS',
            'module' => 'SETTINGS',
            'description' => 'Updated system and company settings',
            'ip_address' => $request->ip(),
        ]);

        return response()->json(['success' => true, 'message' => 'Settings updated successfully']);
    }

    public function backup(Request $request)
    {
        $dbName = config('database.connections.mysql.database');
        $tables = DB::select('SHOW TABLES');
        $keyName = "Tables_in_" . $dbName;

        $sqlScript = "-- Dreamway Textile POS Database Backup\n";
        $sqlScript .= "-- Generated at: " . date('Y-m-d H:i:s') . "\n";
        $sqlScript .= "SET FOREIGN_KEY_CHECKS=0;\n\n";

        foreach ($tables as $table) {
            $tableName = $table->$keyName;
            $createTable = DB::select("SHOW CREATE TABLE `$tableName`")[0]->{'Create Table'};
            $sqlScript .= "DROP TABLE IF EXISTS `$tableName`;\n";
            $sqlScript .= $createTable . ";\n\n";

            $rows = DB::table($tableName)->get();
            foreach ($rows as $row) {
                $values = array_map(function ($value) {
                    if (is_null($value)) return "NULL";
                    return "'" . addslashes((string)$value) . "'";
                }, (array)$row);
                if (count($values) > 0) {
                    $sqlScript .= "INSERT INTO `$tableName` VALUES (" . implode(", ", $values) . ");\n";
                }
            }
            $sqlScript .= "\n\n";
        }

        $sqlScript .= "SET FOREIGN_KEY_CHECKS=1;\n";

        AuditLog::create([
            'user_id' => $request->user()?->id,
            'user_name' => $request->user()?->name,
            'action' => 'DATABASE_BACKUP',
            'module' => 'SYSTEM',
            'description' => 'Generated full database backup .sql file',
            'ip_address' => $request->ip(),
        ]);

        $fileName = "textile_pos_backup_" . date('Y_m_d') . ".sql";
        return response($sqlScript, 200, [
            'Content-Type' => 'text/plain',
            'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
        ]);
    }

    public function restore(Request $request)
    {
        $request->validate([
            'backup_file' => 'required|file',
        ]);

        $file = $request->file('backup_file');
        $sql = file_get_contents($file->getRealPath());

        DB::unprepared($sql);

        AuditLog::create([
            'user_id' => $request->user()?->id,
            'user_name' => $request->user()?->name,
            'action' => 'DATABASE_RESTORE',
            'module' => 'SYSTEM',
            'description' => 'Restored database state from backup .sql file',
            'ip_address' => $request->ip(),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Database state restored successfully from SQL file!',
        ]);
    }
}
