<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\Society;
use App\Models\Tender;
use App\Models\Unit;
use App\Models\MaintenanceBill;
use App\Models\AccountLedger;

class SampleDataSeeder extends Seeder
{
    public function run()
    {
        // Clear existing data
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        DB::table('tender_bids')->truncate();
        DB::table('tenders')->truncate();
        DB::table('maintenance_bills')->truncate();
        DB::table('account_ledgers')->truncate();
        DB::table('member_units')->truncate();
        DB::table('units')->truncate();
        DB::table('users')->truncate();
        DB::table('societies')->truncate();
        // Truncate tables to reset auto-increments

        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        // Create Societies
        $society1 = Society::create([
            'name' => 'Green Valley Residency',
            'registration_number' => 'GVR-2020-001',
            'address' => '123 Green Valley Road',
            'city' => 'Mumbai',
            'state' => 'Maharashtra',
            'pincode' => '400001',
            'email' => 'admin@greenvalley.com',
            'contact_no' => '+91-9876543210'
        ]);

        $society2 = Society::create([
            'name' => 'Sunrise Towers',
            'registration_number' => 'SRT-2019-045',
            'address' => '456 Sunrise Avenue',
            'city' => 'Pune',
            'state' => 'Maharashtra',
            'pincode' => '411001',
            'email' => 'contact@sunrisetowers.com',
            'contact_no' => '+91-9123456789'
        ]);

        $societies = [$society1, $society2];

        // Create Super Admin
        User::create([
            'name' => 'System Administrator',
            'email' => 'admin@system.com',
            'password' => Hash::make('password'),
            'role' => 'super_admin',
            'api_token' => Str::random(60)
        ]);

        // Create Society Admins
        $admin1 = User::create([
            'society_id' => $society1->id,
            'name' => 'Rajesh Kumar',
            'email' => 'rajesh@greenvalley.com',
            'password' => Hash::make('password'),
            'role' => 'society_admin',
            'phone' => '+91-9876543211'
        ]);

        if ('rajesh@greenvalley.com' !== 'admin@greenvalley.com') {
            User::create([
                'society_id' => $society1->id,
                'name' => 'Green Valley Admin',
                'email' => 'admin@greenvalley.com',
                'password' => Hash::make('password'),
                'role' => 'society_admin',
                'phone' => '+91-9876543200'
            ]);
        }

        $admin2 = User::create([
            'society_id' => $society2->id,
            'name' => 'Priya Sharma',
            'email' => 'priya@sunrisetowers.com',
            'password' => Hash::make('password'),
            'role' => 'society_admin',
            'phone' => '+91-9123456780'
        ]);

        // Create Vendors
        $vendorsData = [
            [
                'society_id' => $society1->id,
                'name' => 'ABC Construction Ltd',
                'email' => 'contact@abcconstruction.com',
                'role' => 'vendor',
                'vendor_company_name' => 'ABC Construction Private Limited',
                'vendor_type' => 'Construction',
                'vendor_gst_number' => '27AABCU9603R1ZM',
                'vendor_pan_number' => 'AABCU9603R',
                'vendor_registration_date' => '2018-01-15',
                'vendor_status' => 'active',
                'vendor_rating' => 4.5,
                'vendor_completed_projects' => 12,
                'phone' => '+91-9876543212'
            ],
            [
                'society_id' => $society1->id,
                'name' => 'Elite Elevators Pvt Ltd',
                'email' => 'sales@eliteelevators.com',
                'role' => 'vendor',
                'vendor_company_name' => 'Elite Elevators Private Limited',
                'vendor_type' => 'Maintenance',
                'vendor_gst_number' => '27AABCE1234R1ZM',
                'vendor_pan_number' => 'AABCE1234R',
                'vendor_registration_date' => '2019-06-20',
                'vendor_status' => 'active',
                'vendor_rating' => 4.8,
                'vendor_completed_projects' => 25,
                'phone' => '+91-9876543213'
            ],
            [
                'society_id' => $society2->id,
                'name' => 'Quick Fix Services',
                'email' => 'info@quickfix.com',
                'role' => 'vendor',
                'vendor_company_name' => 'Quick Fix Services LLP',
                'vendor_type' => 'Plumbing',
                'vendor_gst_number' => '27AABCQ5678R1ZM',
                'vendor_pan_number' => 'AABCQ5678R',
                'vendor_registration_date' => '2020-03-10',
                'vendor_status' => 'suspended',
                'vendor_rating' => 3.2,
                'vendor_completed_projects' => 5,
                'suspended_until' => now()->addDays(30)->toDateString(),
                'blocked_reason' => 'Delayed project completion',
                'phone' => '+91-9123456781'
            ]
        ];

        $createdVendors = [];
        foreach ($vendorsData as $vData) {
            $createdVendors[] = User::create(array_merge($vData, [
                'password' => Hash::make('password'),
                'api_token' => Str::random(60)
            ]));
        }

        // Create Members
        for ($i = 1; $i <= 10; $i++) {
            User::create([
                'society_id' => $i <= 5 ? $society1->id : $society2->id,
                'name' => "Member {$i}",
                'email' => "member{$i}@example.com",
                'password' => Hash::make('password'),
                'role' => 'member',
                'phone' => '+91-98765432' . (14 + $i),
                'api_token' => Str::random(60)
            ]);
        }

        // Create Units
        foreach ($societies as $soc) {
            for ($floor = 1; $floor <= 5; $floor++) {
                for ($unit = 1; $unit <= 4; $unit++) {
                    Unit::create([
                        'society_id' => $soc->id,
                        'unit_number' => "A-{$floor}0{$unit}",
                        'wing' => 'A',
                        'floor' => $floor,
                        'unit_type' => 'flat',
                        'area_sqft' => 1200 + ($floor * 50),
                        'monthly_maintenance' => 5000 + ($floor * 200),
                        'status' => $unit <= 3 ? 'occupied' : 'vacant'
                    ]);
                }
            }
        }

        // Create Tenders
        $tender1 = Tender::create([
            'society_id' => $society1->id,
            'created_by' => $admin1->id,
            'title' => 'Elevator Modernization Project',
            'category' => 'construction',
            'description' => 'Complete modernization of 2 elevators including new control systems',
            'budget' => 500000,
            'minimum_bid_amount' => 400000,
            'maximum_bid_amount' => 600000,
            'deadline' => now()->addDays(30)->toDateString(),
            'bid_submission_start' => now()->toDateTimeString(),
            'bid_submission_end' => now()->addDays(15)->toDateTimeString(),
            'status' => 'open',
            'approval_status' => 'open',
            'is_suspended' => false
        ]);

        $tender2 = Tender::create([
            'society_id' => $society1->id,
            'created_by' => $admin1->id,
            'title' => 'Annual Painting Contract',
            'category' => 'maintenance',
            'description' => 'Painting of common areas and exterior walls',
            'budget' => 150000,
            'minimum_bid_amount' => 120000,
            'maximum_bid_amount' => 180000,
            'deadline' => now()->addDays(20)->toDateString(),
            'bid_submission_start' => now()->toDateTimeString(),
            'bid_submission_end' => now()->addDays(10)->toDateTimeString(),
            'status' => 'open',
            'approval_status' => 'open',
            'is_suspended' => false
        ]);

        // Create Bids
        if (count($createdVendors) >= 2) {
            DB::table('tender_bids')->insert([
                ['tender_id' => $tender1->id, 'vendor_id' => $createdVendors[0]->id, 'quoted_amount' => 480000, 'proposal_details' => 'Bid A', 'status' => 'submitted', 'created_at' => now(), 'updated_at' => now()],
                ['tender_id' => $tender1->id, 'vendor_id' => $createdVendors[1]->id, 'quoted_amount' => 450000, 'proposal_details' => 'Bid B', 'status' => 'submitted', 'created_at' => now(), 'updated_at' => now()],
            ]);
        }

        // Create Finance Ledger Entries
        for ($i = 1; $i <= 20; $i++) {
            AccountLedger::create([
                'society_id' => $i <= 10 ? $society1->id : $society2->id,
                'type' => $i % 3 == 0 ? 'debit' : 'credit',
                'amount' => rand(5000, 50000),
                'category' => $i % 3 == 0 ? 'Maintenance Expense' : 'Maintenance Collection',
                'description' => $i % 3 == 0 ? 'Elevator repair payment' : 'Monthly maintenance - Unit A-' . (100 + $i),
                'transaction_date' => now()->subDays(rand(1, 30))->toDateString()
            ]);
        }

        // Create Maintenance Bills
        $currentMonth = now()->format('Y-m');
        $units = Unit::where('status', 'occupied')->get();
        foreach ($units as $unit) {
            MaintenanceBill::create([
                'society_id' => $unit->society_id,
                'unit_id' => $unit->id,
                'billing_month' => $currentMonth,
                'amount' => $unit->monthly_maintenance,
                'status' => rand(0, 1) ? 'paid' : 'pending',
                'paid_at' => rand(0, 1) ? now() : null
            ]);
        }

        echo "Sample data seeded using Eloquent with Standardized IDs successfully!\n";
    }
}
