<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$success_message = "";
$error_message = "";

// Add Supplier
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_supplier'])) {
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $contact_person = mysqli_real_escape_string($conn, $_POST['contact_person']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $opening_balance = mysqli_real_escape_string($conn, $_POST['opening_balance']);
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($name) || empty($phone)) {
        $error_message = "Name and Phone are required!";
    } elseif(!is_numeric($opening_balance) || $opening_balance < 0) {
        $error_message = "Opening balance must be a valid positive number!";
    } else {
        $sql = "INSERT INTO suppliers (name, contact_person, phone, email, address, opening_balance, current_balance, date_time) 
                VALUES ('$name', '$contact_person', '$phone', '$email', '$address', '$opening_balance', '$opening_balance', '$date_time')";
        
        if(mysqli_query($conn, $sql)) {
            $success_message = "Supplier added successfully with opening balance of Rs " . number_format($opening_balance, 2);
            
            if($opening_balance > 0) {
                $supplier_id = mysqli_insert_id($conn);
                $record_sql = "INSERT INTO supplier_payments (supplier_id, amount, notes, payment_method, date_time) 
                               VALUES ('$supplier_id', '$opening_balance', 'Opening balance added', 'opening_balance', '$date_time')";
                mysqli_query($conn, $record_sql);
            }
        } else {
            $error_message = "Error: " . mysqli_error($conn);
        }
    }
}

// Delete Supplier
if(isset($_GET['delete'])) {
    $delete_id = mysqli_real_escape_string($conn, $_GET['delete']);
    
    $check_sql = "SELECT id FROM purchases WHERE supplier_id='$delete_id'";
    $check_result = mysqli_query($conn, $check_sql);
    
    if(mysqli_num_rows($check_result) > 0) {
        $error_message = "Cannot delete! Supplier has purchase records.";
    } else {
        $sql = "DELETE FROM suppliers WHERE id='$delete_id'";
        if(mysqli_query($conn, $sql)) {
            $success_message = "Supplier deleted successfully!";
        } else {
            $error_message = "Error deleting supplier";
        }
    }
}

// Get all suppliers
$sql = "SELECT * FROM suppliers ORDER BY id DESC";
$result = mysqli_query($conn, $sql);

// Get statistics
$total_suppliers = mysqli_num_rows($result);
$total_balance = 0;
$suppliers_with_balance = 0;

while($row = mysqli_fetch_assoc($result)) {
    $total_balance += $row['current_balance'];
    if($row['current_balance'] > 0) {
        $suppliers_with_balance++;
    }
}
mysqli_data_seek($result, 0);
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<div class="suppliers-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-truck"></i> Supplier Management</h2>
            <p>Manage fuel suppliers, track balances and purchase history</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span><?php echo $total_suppliers; ?> Total Suppliers</span>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-truck"></i></div>
            <div class="stat-info">
                <h3><?php echo $total_suppliers; ?></h3>
                <p>Total Suppliers</p>
                <span class="stat-trend">Registered Suppliers</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-rupee-sign"></i></div>
            <div class="stat-info">
                <h3>Rs <?php echo number_format($total_balance, 2); ?></h3>
                <p>Total Outstanding</p>
                <span class="stat-trend">Total Credit Balance</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-hand-holding-usd"></i></div>
            <div class="stat-info">
                <h3><?php echo $suppliers_with_balance; ?></h3>
                <p>Active Credit Accounts</p>
                <span class="stat-trend">Suppliers with Balance</span>
            </div>
        </div>
    </div>

    <!-- Alerts -->
    <?php if($success_message): ?>
        <div class="alert-custom alert-success">
            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger">
            <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>
    
    <div class="content-grid">
        <!-- Add Supplier Form -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-plus-circle"></i>
                <h4>Add New Supplier</h4>
            </div>
            <div class="form-card-body">
                <form method="POST" action="">
                    <div class="input-group-custom">
                        <label><i class="fas fa-building"></i> Supplier Name <span class="required">*</span></label>
                        <input type="text" name="name" class="form-control-modern" required placeholder="Enter full name">
                        <small class="input-help">Full name of the supplier</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-user"></i> Contact Person</label>
                        <input type="text" name="contact_person" class="form-control-modern" placeholder="Contact person name">
                        <small class="input-help">Person to contact at supplier</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-phone"></i> Phone Number <span class="required">*</span></label>
                        <input type="tel" name="phone" class="form-control-modern" required placeholder="03XXXXXXXXX">
                        <small class="input-help">Active phone number for contact</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-envelope"></i> Email Address</label>
                        <input type="email" name="email" class="form-control-modern" placeholder="Email address">
                        <small class="input-help">Email address (optional)</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-map-marker-alt"></i> Address</label>
                        <textarea name="address" class="form-control-modern" rows="2" placeholder="Supplier address"></textarea>
                        <small class="input-help">Complete address of supplier</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-rupee-sign"></i> Opening Balance (Rs)</label>
                        <input type="number" step="0.01" name="opening_balance" class="form-control-modern" value="0" placeholder="0.00">
                        <small class="input-help">Previous outstanding balance (if any)</small>
                    </div>
                    
                    <div class="balance-preview" id="balancePreview" style="display: none;">
                        <div class="preview-row">
                            <span><i class="fas fa-info-circle"></i> Opening Balance:</span>
                            <strong id="previewAmount">Rs 0.00</strong>
                        </div>
                        <div class="preview-row">
                            <span><i class="fas fa-chart-line"></i> Status:</span>
                            <strong id="previewStatus">Clear</strong>
                        </div>
                    </div>
                    
                    <button type="submit" name="add_supplier" class="btn-submit">
                        <i class="fas fa-save"></i> Add Supplier
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Suppliers List -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-list"></i>
                    <h4>Suppliers List</h4>
                </div>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" placeholder="Search supplier..." class="search-input">
                </div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="suppliersTable">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Supplier Name</th>
                                <th>Phone</th>
                                <th>Email</th>
                                <th>Opening Balance</th>
                                <th>Current Balance</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($result) > 0): ?>
                                <?php while($row = mysqli_fetch_assoc($result)): 
                                    $balance_status = $row['current_balance'] > 0 ? 'due' : 'clear';
                                    $balance_text = $row['current_balance'] > 0 ? 'Due' : 'Clear';
                                    $balance_icon = $row['current_balance'] > 0 ? 'fa-hourglass-half' : 'fa-check-circle';
                                ?>
                                    <tr>
                                        <td data-label="ID">#<?php echo $row['id']; ?></td>
                                        <td data-label="Supplier Name">
                                            <div class="supplier-name-cell">
                                                <div class="avatar"><i class="fas fa-building"></i></div>
                                                <strong><?php echo htmlspecialchars($row['name']); ?></strong>
                                            </div>
                                        </div>
                                        <td data-label="Phone">
                                            <div class="phone-cell"><i class="fas fa-phone-alt"></i> <?php echo htmlspecialchars($row['phone']); ?></div>
                                        </div>
                                        <td data-label="Email">
                                            <div class="email-cell"><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($row['email'] ?: '—'); ?></div>
                                        </div>
                                        <td data-label="Opening Balance">Rs <?php echo number_format($row['opening_balance'], 2); ?></div>
                                        <td data-label="Current Balance">
                                            <div class="balance-cell <?php echo $balance_status; ?>">Rs <?php echo number_format($row['current_balance'], 2); ?></div>
                                        </div>
                                        <td data-label="Status">
                                            <span class="status-badge <?php echo $balance_status; ?>">
                                                <i class="fas <?php echo $balance_icon; ?>"></i> <?php echo $balance_text; ?>
                                            </span>
                                        </div>
                                        <td data-label="Actions">
                                            <div class="action-buttons">
                                                <!--<a href="supplier_payments.php?supplier_id=<?php echo $row['id']; ?>" class="btn-action btn-payment" title="Make Payment"><i class="fas fa-hand-holding-usd"></i></a>-->
                                                <a href="supplier_ledger.php?id=<?php echo $row['id']; ?>" class="btn-action btn-ledger" title="View Ledger"><i class="fas fa-book"></i></a>
                                                <a href="?delete=<?php echo $row['id']; ?>" class="btn-action btn-delete" onclick="return confirm('Delete this supplier?')" title="Delete"><i class="fas fa-trash"></i></a>
                                            </div>
                                        </div>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="8" class="empty-state"><i class="fas fa-truck"></i><p>No suppliers found</p><small>Click "Add New Supplier" to get started</small></div></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Suppliers Page Styles - Page Specific Only */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');

* {
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #f5f7fb;
    overflow-x: hidden;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.stat-info h3,
.form-card-header h4,
.header-info h4,
.modern-table th {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    background: #f5f7fb;
}

.suppliers-container {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 16px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    color: #fff;
    margin: 0 0 4px 0;
    font-size: 22px;
}

.page-header p {
    color: rgba(255,255,255,0.9);
    margin: 0;
    font-size: 12px;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 18px;
    border-radius: 40px;
    font-weight: 600;
    font-size: 12px;
}

/* Statistics Row */
.stats-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 20px;
    width: 100%;
}

.stat-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    border: 1px solid #f0f0f0;
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 18px rgba(160,70,87,0.1);
    border-color: #A04657;
}

.stat-icon {
    width: 52px;
    height: 52px;
    background: rgba(160,70,87,0.1);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.stat-icon i {
    font-size: 26px;
    color: #A04657;
}

.stat-info h3 {
    font-size: 24px;
    margin: 0;
    font-weight: 700;
    color: #1a1a2e;
}

.stat-info p {
    margin: 3px 0 0;
    color: #666;
    font-size: 11px;
}

.stat-trend {
    font-size: 10px;
    color: #999;
    display: block;
    margin-top: 2px;
}

/* Alerts */
.alert-custom {
    padding: 12px 20px;
    border-radius: 14px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 13px;
    width: 100%;
}

.alert-success {
    background: #e8f5e9;
    color: #2e7d32;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #ffebee;
    color: #c62828;
    border-left: 4px solid #dc3545;
}

.close-alert {
    background: none;
    border: none;
    font-size: 22px;
    cursor: pointer;
    opacity: 0.5;
}

/* Content Grid */
.content-grid {
    display: grid;
    grid-template-columns: 380px 1fr;
    gap: 20px;
    width: 100%;
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    height: fit-content;
}

.form-card-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    padding: 14px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #fff;
}

.form-card-header i {
    font-size: 18px;
}

.form-card-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.form-card-body {
    padding: 20px;
}

.input-group-custom {
    margin-bottom: 16px;
}

.input-group-custom label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
    color: #333;
    font-size: 12px;
}

.input-group-custom label i {
    color: #A04657;
    margin-right: 5px;
}

.required {
    color: #dc3545;
}

.form-control-modern {
    width: 100%;
    padding: 9px 12px;
    border: 2px solid #e8e8e8;
    border-radius: 10px;
    font-size: 13px;
    transition: all 0.2s;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
}

.input-help {
    display: block;
    font-size: 10px;
    color: #999;
    margin-top: 4px;
}

.balance-preview {
    background: #f8f9ff;
    border-radius: 10px;
    padding: 10px;
    margin-bottom: 16px;
    border: 1px solid #e8e8ff;
}

.preview-row {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
    font-size: 11px;
}

.preview-row strong {
    color: #A04657;
}

.btn-submit {
    width: 100%;
    padding: 10px;
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    width: 100%;
}

.table-card-header {
    padding: 12px 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.header-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-info i {
    font-size: 18px;
    color: #A04657;
}

.header-info h4 {
    margin: 0;
    font-size: 15px;
}

.table-search {
    position: relative;
}

.table-search i {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
    font-size: 11px;
}

.search-input {
    padding: 7px 12px 7px 32px;
    border: 2px solid #e8e8e8;
    border-radius: 30px;
    width: 200px;
    font-size: 12px;
}

.search-input:focus {
    border-color: #A04657;
    outline: none;
}

.table-responsive {
    overflow-x: auto;
    width: 100%;
}

.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 800px;
}

.modern-table th {
    padding: 10px 12px;
    background: #f8f9fa;
    font-weight: 700;
    color: #555;
    font-size: 11px;
    border-bottom: 1px solid #e8e8e8;
}

.modern-table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-size: 12px;
}

.supplier-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.supplier-name-cell .avatar {
    width: 28px;
    height: 28px;
    background: rgba(160,70,87,0.1);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.supplier-name-cell .avatar i {
    font-size: 14px;
    color: #A04657;
}

.balance-cell.due {
    color: #dc3545;
    font-weight: 700;
}

.balance-cell.clear {
    color: #28a745;
    font-weight: 700;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 3px 10px;
    border-radius: 30px;
    font-size: 10px;
    font-weight: 600;
}

.status-badge.due {
    background: #ffebee;
    color: #c62828;
}

.status-badge.clear {
    background: #e8f5e9;
    color: #2e7d32;
}

.action-buttons {
    display: flex;
    gap: 6px;
}

.btn-action {
    width: 28px;
    height: 28px;
    border-radius: 8px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    transition: all 0.2s;
}

.btn-payment {
    background: #e3f2fd;
    color: #1976d2;
}

.btn-payment:hover {
    background: #1976d2;
    color: #fff;
}

.btn-ledger {
    background: #e8eaf6;
    color: #3f51b5;
}

.btn-ledger:hover {
    background: #3f51b5;
    color: #fff;
}

.btn-delete {
    background: #ffebee;
    color: #d32f2f;
}

.btn-delete:hover {
    background: #d32f2f;
    color: #fff;
}

.empty-state {
    text-align: center;
    padding: 40px !important;
}

.empty-state i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.4;
    margin-bottom: 12px;
    display: block;
}

/* Responsive */
@media (max-width: 1100px) {
    .content-grid {
        grid-template-columns: 1fr;
    }
    .stats-row {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 992px) {
    .main-content {
        margin-left: 0;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .stats-row {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .table-card-header {
        flex-direction: column;
        align-items: stretch;
    }
    .search-input {
        width: 100%;
    }
    .form-card-body {
        padding: 16px;
    }
    .stat-card {
        padding: 12px 16px;
    }
    .stat-icon {
        width: 44px;
        height: 44px;
    }
    .stat-icon i {
        font-size: 22px;
    }
    .stat-info h3 {
        font-size: 20px;
    }
    .modern-table th {
        display: none;
    }
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 45%;
        position: relative;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 12px;
        width: 40%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #A04657;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 10px;
        overflow: hidden;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

<script>
// Table search
const searchInput = document.getElementById('tableSearch');
if(searchInput) {
    searchInput.addEventListener('keyup', function() {
        let value = this.value.toLowerCase();
        let rows = document.querySelectorAll('#suppliersTable tbody tr');
        rows.forEach(row => {
            row.style.display = row.textContent.toLowerCase().includes(value) ? '' : 'none';
        });
    });
}

// Opening balance preview
const balanceInput = document.querySelector('input[name="opening_balance"]');
const balancePreview = document.getElementById('balancePreview');
const previewAmount = document.getElementById('previewAmount');
const previewStatus = document.getElementById('previewStatus');

function updateBalancePreview() {
    let balance = parseFloat(balanceInput?.value) || 0;
    
    if(balance > 0 && balancePreview) {
        balancePreview.style.display = 'block';
        previewAmount.innerHTML = 'Rs ' + balance.toFixed(2);
        previewStatus.innerHTML = 'Due (Previous outstanding)';
        previewStatus.style.color = '#dc3545';
    } else if(balancePreview) {
        balancePreview.style.display = 'none';
    }
}

if(balanceInput) {
    balanceInput.addEventListener('input', updateBalancePreview);
}
</script>

<?php include('../includes/ft.php'); ?>