<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Stocktransaction;
use App\Models\StockTransactionSo;
use App\Models\Substocktransaction;
use App\Models\Cashtransaction;
use App\Models\Subcashtransaction;
use App\Models\Credit;
use App\Models\CreditCashTransaction;
use App\Models\Akun;
use App\Models\Attachment;
use App\Models\ContactPoint;
use App\Models\ErrorLog;
use App\Models\PointTransaction;
use Illuminate\Support\Facades\File;

class CleanController extends Controller
{
    public function clean(Request $request)
    {
        $backupController = new BackupController();
        $response = $backupController->runBackup();

        if (!$response->getData()->success) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menjalankan backup database.',
            ], 500);
        }
        $akun = Product::whereNotNull('name')->where('category', '<>', 'service')->update(['qty' => 0]);
        $akun = Stocktransaction::whereNotNull('id')->delete();
        $akun = StockTransactionSo::whereNotNull('id')->delete();
        $akun = Substocktransaction::whereNotNull('id')->delete();
        $akun = Cashtransaction::whereNotNull('id')->delete();
        $akun = Subcashtransaction::whereNotNull('id')->delete();
        $akun = Credit::whereNotNull('id')->delete();
        $akun = CreditCashTransaction::whereNotNull('id')->delete();
        $akun = Akun::whereNotNull('name')->update(['total' => 0]);
        $akun = Attachment::whereNotNull('id')->delete();
        $akun = PointTransaction::whereNotNull('id')->delete();
        $akun = ErrorLog::whereNotNull('id')->delete();

        // Reset Point
        $contactpoints = ContactPoint::all();
        foreach ($contactpoints as $item) {
            $item->total_point = 0;
            $item->save();
        }

        $attachmentPath = storage_path('app/attachment');
        if (File::exists($attachmentPath)) {
            File::cleanDirectory($attachmentPath);
        }

        return response()->json([
            'success' => true,
            'message' => 'Data berhasil dibersihkan.',
        ]);
    }
}
