<?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\CorporateIncomeTax;
use App\Models\ErrorLog;
use App\Models\PointTransaction;
use App\Models\Production;
use App\Models\ProductionCost;
use App\Models\ProductionCostSetting;
use App\Models\Substockopname;
use App\Models\TaxFiscalCorrection;
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();
        $akun = Substockopname::whereNotNull('id')->delete();
        $akun = Production::whereNotNull('id')->delete();
        $akun = ProductionCost::whereNotNull('id')->delete();
        $akun = CorporateIncomeTax::whereNotNull('id')->delete();
        $akun = TaxFiscalCorrection::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.',
        ]);
    }
}
