<?php
/**
 * VENDOR PROFILE PAGE
 * File: modules/vendor/profile.php
 * View and edit vendor profile information
 */

require_once '../app/Core/init.php';

// Require vendor authentication
Auth::requireVendor();

// Initialize models
$vendor = new Vendor();
$upload = new Upload();

// Get vendor details
$vendor_id = Auth::id();
$vendor_data = $vendor->getByUserId($vendor_id);


// Get bank details from users table
$db = Database::getInstance();
$user_bank = $db->fetch("SELECT bank_name, account_name, account_number FROM users WHERE id = ?", [$vendor_id]);

// Merge bank details into vendor_data for form display
if ($vendor_data && $user_bank) {
    $vendor_data['bank_name'] = $user_bank['bank_name'];
    $vendor_data['account_name'] = $user_bank['account_name'];
    $vendor_data['account_number'] = $user_bank['account_number'];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token
    if (!Security::validateToken($_POST['csrf_token'] ?? '')) {
        flash('error', 'Invalid security token. Please try again.', 'danger');
        redirect($_SERVER['PHP_SELF']);
    }
    
    // Collect and clean input data
    $data = [
        'business_name' => Security::clean($_POST['business_name'] ?? ''),
        'business_type' => Security::clean($_POST['business_type'] ?? ''),
        'phone' => Security::clean($_POST['phone'] ?? ''),
        'address' => Security::clean($_POST['address'] ?? ''),
        'city' => Security::clean($_POST['city'] ?? ''),
        'state' => Security::clean($_POST['state'] ?? ''),
        'business_description' => Security::clean($_POST['business_description'] ?? ''),
        'bank_name' => Security::clean($_POST['bank_name'] ?? ''),
        'account_number' => Security::clean($_POST['account_number'] ?? ''),
        'account_name' => Security::clean($_POST['account_name'] ?? '')
    ];
    
    // Validation
    $errors = [];
    
    if (empty($data['business_name'])) {
        $errors[] = 'Business name is required';
    }
    
    if (empty($data['phone'])) {
        $errors[] = 'Phone number is required';
    } elseif (!Security::validatePhone($data['phone'])) {
        $errors[] = 'Invalid phone number format';
    }
    
    if (empty($data['address'])) {
        $errors[] = 'Business address is required';
    }
    
    if (empty($data['city'])) {
        $errors[] = 'City is required';
    }
    
    if (empty($data['state'])) {
        $errors[] = 'State is required';
    }
    
    // Bank details validation (if provided)
    if (!empty($data['account_number'])) {
        if (!is_numeric($data['account_number']) || strlen($data['account_number']) != 10) {
            $errors[] = 'Account number must be exactly 10 digits';
        }
        
        if (empty($data['bank_name'])) {
            $errors[] = 'Bank name is required when account number is provided';
        }
        
        if (empty($data['account_name'])) {
            $errors[] = 'Account name is required when account number is provided';
        }
    }
    
    // Handle logo upload
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $logo_validation = Security::validateFile($_FILES['logo'], ALLOWED_IMAGE_TYPES, MAX_FILE_SIZE);
        
        if ($logo_validation['success']) {
            $logo_result = $upload->uploadImage($_FILES['logo'], 'profiles');
            
            if ($logo_result['success']) {
                $data['logo'] = $logo_result['filename'];
                
                // Delete old logo if exists
                if (!empty($vendor_data['logo'])) {
                    $upload->deleteFile('profiles/' . $vendor_data['logo']);
                }
            } else {
                $errors[] = $logo_result['message'];
            }
        } else {
            $errors[] = $logo_validation['message'];
        }
    }
    
    // Handle business document upload
    if (isset($_FILES['business_document']) && $_FILES['business_document']['error'] === UPLOAD_ERR_OK) {
        $doc_validation = Security::validateFile($_FILES['business_document'], ALLOWED_DOCUMENT_TYPES . ',' . ALLOWED_IMAGE_TYPES, MAX_FILE_SIZE);
        
        if ($doc_validation['success']) {
            $doc_result = $upload->document($_FILES['business_document'], 'documents');
            
            if ($doc_result['success']) {
                $data['business_document'] = $doc_result['filename'];
                
                // Delete old document if exists
                if (!empty($vendor_data['business_document'])) {
                    $upload->deleteFile('documents/' . $vendor_data['business_document']);
                }
            } else {
                $errors[] = $doc_result['message'];
            }
        } else {
            $errors[] = $doc_validation['message'];
        }
    }
    
    // Handle ID document upload
    if (isset($_FILES['id_document']) && $_FILES['id_document']['error'] === UPLOAD_ERR_OK) {
        $id_validation = Security::validateFile($_FILES['id_document'], ALLOWED_DOCUMENT_TYPES . ',' . ALLOWED_IMAGE_TYPES, MAX_FILE_SIZE);
        
        if ($id_validation['success']) {
            $id_result = $upload->document($_FILES['id_document'], 'documents');
            
            if ($id_result['success']) {
                $data['id_document'] = $id_result['filename'];
                
                // Delete old document if exists
                if (!empty($vendor_data['id_document'])) {
                    $upload->deleteFile('documents/' . $vendor_data['id_document']);
                }
            } else {
                $errors[] = $id_result['message'];
            }
        } else {
            $errors[] = $id_validation['message'];
        }
    }
    
    
    // Update profile if no errors
    if (empty($errors)) {
        $db->beginTransaction();
        
        try {
            // Separate vendor data from bank data
            $vendor_update_data = [
                'business_name' => $data['business_name'],
                'business_type' => $data['business_type'],
                'phone' => $data['phone'],
                'address' => $data['address'],
                'city' => $data['city'],
                'state' => $data['state'],
                'business_description' => $data['business_description']
            ];
            
            // Add file uploads if present
            if (isset($data['logo'])) {
                $vendor_update_data['logo'] = $data['logo'];
            }
            if (isset($data['business_document'])) {
                $vendor_update_data['business_document'] = $data['business_document'];
            }
            if (isset($data['id_document'])) {
                $vendor_update_data['id_document'] = $data['id_document'];
            }
            
            if ($vendor_data) {
                // Update existing vendor profile
                $vendor_result = $vendor->update($vendor_data['id'], $vendor_update_data);
            } else {
                // Create new profile (first time)
                $vendor_update_data['user_id'] = $vendor_id;
                $vendor_result = $vendor->create($vendor_update_data);
            }
            
            // Update bank details in users table
            $bank_result = $db->execute("
                UPDATE users 
                SET bank_name = ?, 
                    account_number = ?, 
                    account_name = ?,
                    updated_at = NOW()
                WHERE id = ?
            ", [
                $data['bank_name'],
                $data['account_number'],
                $data['account_name'],
                $vendor_id
            ]);
            
            if ($vendor_result && $bank_result) {
                $db->commit();
                flash('success', 'Profile and bank details updated successfully!', 'success');
                redirect($_SERVER['PHP_SELF']);
            } else {
                $db->rollback();
                flash('error', 'Failed to update profile. Please try again.', 'danger');
            }
            
        } catch (Exception $e) {
            $db->rollback();
            flash('error', 'Database error: ' . $e->getMessage(), 'danger');
        }
    } else {
        foreach ($errors as $error) {
            flash('error', $error, 'danger');
        }
        
        // Store old input
        $_SESSION['old'] = $data;
    }
}

// Nigerian states
$nigerian_states = [
    'Abia', 'Adamawa', 'Akwa Ibom', 'Anambra', 'Bauchi', 'Bayelsa', 'Benue', 'Borno', 'Cross River',
    'Delta', 'Ebonyi', 'Edo', 'Ekiti', 'Enugu', 'FCT', 'Gombe', 'Imo', 'Jigawa', 'Kaduna', 'Kano',
    'Katsina', 'Kebbi', 'Kogi', 'Kwara', 'Lagos', 'Nasarawa', 'Niger', 'Ogun', 'Ondo', 'Osun',
    'Oyo', 'Plateau', 'Rivers', 'Sokoto', 'Taraba', 'Yobe', 'Zamfara'
];

// Nigerian banks
$nigerian_banks = [
    'Access Bank', 'Citibank', 'Ecobank', 'Fidelity Bank', 'First Bank', 'First City Monument Bank (FCMB)',
    'Globus Bank', 'Guaranty Trust Bank (GTBank)', 'Heritage Bank', 'Keystone Bank', 'Polaris Bank',
    'Providus Bank', 'Stanbic IBTC Bank', 'Standard Chartered Bank', 'Sterling Bank', 'SunTrust Bank',
    'Union Bank', 'United Bank for Africa (UBA)', 'Unity Bank', 'Wema Bank', 'Zenith Bank'
];

// Page variables
$page_title = "Vendor Profile";
$active_menu = "profile";

// Include header
include '../templates/layouts/vendor/header.php';
?>

<div class="main-content">
    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-user-circle"></i> My Profile</h1>
            <p class="text-muted">Manage your business profile and bank details</p>
        </div>
    </div>

    <?php if ($vendor_data && $vendor_data['approval_status'] === 'pending'): ?>
        <div class="alert alert-warning">
            <i class="fas fa-clock"></i>
            <strong>Pending Approval:</strong> Your vendor account is awaiting admin approval. You can update your profile while waiting.
        </div>
    <?php elseif ($vendor_data && $vendor_data['approval_status'] === 'rejected'): ?>
        <div class="alert alert-danger">
            <i class="fas fa-times-circle"></i>
            <strong>Account Rejected:</strong> <?= nl2br(esc($vendor_data['rejection_reason'])) ?>
            <br><small>Please update your information and contact support for re-approval.</small>
        </div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
        
        <div class="row">
            <!-- Business Information -->
            <div class="col-lg-8">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-store"></i> Business Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Business Name <span class="text-danger">*</span></label>
                                <input type="text" name="business_name" class="form-control" 
                                       value="<?= esc($vendor_data['business_name'] ?? old('business_name')) ?>" 
                                       required>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Business Type</label>
                                <select name="business_type" class="form-control">
                                    <option value="">Select type</option>
                                    <option value="Individual" <?= ($vendor_data['business_type'] ?? '') === 'Individual' ? 'selected' : '' ?>>Individual</option>
                                    <option value="Company" <?= ($vendor_data['business_type'] ?? '') === 'Company' ? 'selected' : '' ?>>Company</option>
                                    <option value="Partnership" <?= ($vendor_data['business_type'] ?? '') === 'Partnership' ? 'selected' : '' ?>>Partnership</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Phone Number <span class="text-danger">*</span></label>
                                <input type="tel" name="phone" class="form-control" 
                                       value="<?= esc($vendor_data['phone'] ?? old('phone')) ?>" 
                                       placeholder="+234 xxx xxxx xxx" required>
                                <small class="text-muted">Format: +234XXXXXXXXXX or 0XXXXXXXXXX</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email Address</label>
                                <input type="email" class="form-control" value="<?= esc(Auth::email()) ?>" disabled>
                                <small class="text-muted">Cannot be changed</small>
                            </div>
                            
                            <div class="col-12 mb-3">
                                <label class="form-label">Business Address <span class="text-danger">*</span></label>
                                <textarea name="address" class="form-control" rows="2" required><?= esc($vendor_data['address'] ?? old('address')) ?></textarea>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">City <span class="text-danger">*</span></label>
                                <input type="text" name="city" class="form-control" 
                                       value="<?= esc($vendor_data['city'] ?? old('city')) ?>" required>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">State <span class="text-danger">*</span></label>
                                <select name="state" class="form-control" required>
                                    <option value="">Select state</option>
                                    <?php foreach ($nigerian_states as $state): ?>
                                        <option value="<?= $state ?>" <?= ($vendor_data['state'] ?? '') === $state ? 'selected' : '' ?>>
                                            <?= $state ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-12 mb-3">
                                <label class="form-label">Business Description</label>
                                <textarea name="business_description" class="form-control" rows="4" 
                                          placeholder="Tell customers about your business..."><?= esc($vendor_data['business_description'] ?? old('business_description')) ?></textarea>
                                <small class="text-muted">This will be visible to customers on your public profile</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Bank Information -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-university"></i> Bank Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            Bank details are required to receive payments from completed rentals.
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Bank Name</label>
                                <select name="bank_name" class="form-control">
                                    <option value="">Select bank</option>
                                    <?php foreach ($nigerian_banks as $bank): ?>
                                        <option value="<?= $bank ?>" <?= ($vendor_data['bank_name'] ?? '') === $bank ? 'selected' : '' ?>>
                                            <?= $bank ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Account Number</label>
                                <input type="text" name="account_number" class="form-control" 
                                       value="<?= esc($vendor_data['account_number'] ?? old('account_number')) ?>" 
                                       placeholder="10-digit account number" 
                                       maxlength="10" pattern="[0-9]{10}">
                            </div>
                            
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Account Name</label>
                                <input type="text" name="account_name" class="form-control" 
                                       value="<?= esc($vendor_data['account_name'] ?? old('account_name')) ?>" 
                                       placeholder="Account name as registered with bank">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Profile Images & Documents -->
            <div class="col-lg-4">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-image"></i> Business Logo</h5>
                    </div>
                    <div class="card-body text-center">
                        <?php if (!empty($vendor_data['logo'])): ?>
                            <img src="<?= upload('profiles/' . $vendor_data['logo']) ?>" 
                                 alt="Business Logo" 
                                 class="img-fluid rounded mb-3" 
                                 style="max-height: 200px;">
                        <?php else: ?>
                            <div class="bg-light rounded p-5 mb-3">
                                <i class="fas fa-store fa-4x text-muted"></i>
                            </div>
                        <?php endif; ?>
                        
                        <input type="file" name="logo" class="form-control" accept="image/*">
                        <small class="text-muted">JPG, PNG or GIF. Max 5MB</small>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-file-alt"></i> Documents</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Business Document</label>
                            <?php if (!empty($vendor_data['business_document'])): ?>
                                <div class="alert alert-success py-2 mb-2">
                                    <i class="fas fa-check-circle"></i> Document uploaded
                                    <a href="<?= upload('documents/' . $vendor_data['business_document']) ?>" 
                                       target="_blank" class="ms-2">
                                        <i class="fas fa-download"></i> View
                                    </a>
                                </div>
                            <?php endif; ?>
                            <input type="file" name="business_document" class="form-control" accept=".pdf,.doc,.docx,image/*">
                            <small class="text-muted">CAC, Business permit, etc.</small>
                        </div>
                        
                        <div class="mb-0">
                            <label class="form-label">ID Document</label>
                            <?php if (!empty($vendor_data['id_document'])): ?>
                                <div class="alert alert-success py-2 mb-2">
                                    <i class="fas fa-check-circle"></i> Document uploaded
                                    <a href="<?= upload('documents/' . $vendor_data['id_document']) ?>" 
                                       target="_blank" class="ms-2">
                                        <i class="fas fa-download"></i> View
                                    </a>
                                </div>
                            <?php endif; ?>
                            <input type="file" name="id_document" class="form-control" accept=".jpg,.png,.pdf,.doc,.docx,image/*">
                            <small class="text-muted">National ID, Driver's License, etc.</small>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-body">
                        <button type="submit" class="btn btn-primary btn-lg w-100">
                            <i class="fas fa-save"></i> Save Profile
                        </button>
                        
                        <a href="index.php" class="btn btn-outline-secondary w-100 mt-2">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<style>
.alert-success.py-2 {
    font-size: 0.9rem;
}
</style>

<?php 
// Clear old input
unset($_SESSION['old']);
// include '../templates/layouts/vendor/footer.php'; 
?>