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

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

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

// Add Employee
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_employee'])) {
    $employee_name = mysqli_real_escape_string($conn, $_POST['employee_name']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $designation = mysqli_real_escape_string($conn, $_POST['designation']);
    $basic_salary = mysqli_real_escape_string($conn, $_POST['basic_salary']);
    $opening_balance = mysqli_real_escape_string($conn, $_POST['opening_balance']);
    $opening_balance_type = mysqli_real_escape_string($conn, $_POST['opening_balance_type']);
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($employee_name) || empty($phone) || empty($designation)) {
        $error_message = "Please fill all required fields!";
    } elseif($basic_salary < 0) {
        $error_message = "Basic salary cannot be negative!";
    } elseif($opening_balance < 0) {
        $error_message = "Opening balance cannot be negative!";
    } else {
        $check_sql = "SELECT id FROM employees WHERE phone = '$phone'";
        $check_result = mysqli_query($conn, $check_sql);
        
        if(mysqli_num_rows($check_result) > 0) {
            $error_message = "Employee with this phone number already exists!";
        } else {
            // Set initial balance based on opening balance type
            $initial_balance = ($opening_balance_type == 'payable') ? $opening_balance : -$opening_balance;
            
            $sql = "INSERT INTO employees (employee_name, phone, designation, basic_salary, balance, opening_balance, opening_balance_type, date_time) 
                    VALUES ('$employee_name', '$phone', '$designation', '$basic_salary', '$initial_balance', '$opening_balance', '$opening_balance_type', '$date_time')";
            
            if(mysqli_query($conn, $sql)) {
                $employee_id = mysqli_insert_id($conn);
                
                // Add opening balance entry to ledger if opening_balance > 0
                if($opening_balance > 0) {
                    $entry_type = ($opening_balance_type == 'payable') ? 'Opening Payable' : 'Opening Receivable';
                    $ledger_sql = "INSERT INTO employee_ledger (employee_id, entry_type, amount, payment_method, description, date_time) 
                                   VALUES ('$employee_id', '$entry_type', '$opening_balance', 'cash', 'Opening balance added', '$date_time')";
                    mysqli_query($conn, $ledger_sql);
                }
                
                $success_message = "Employee added successfully!";
                
                // Redirect to employee detail page
                header("Location: employee_detail.php?employee_id=" . $employee_id . "&msg=added");
                exit();
            } else {
                $error_message = "Error: " . mysqli_error($conn);
            }
        }
    }
}

// Get all employees
$sql = "SELECT * FROM employees ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
$total_employees = mysqli_num_rows($result);
$total_balance = 0;
while($row = mysqli_fetch_assoc($result)) {
    $total_balance += $row['balance'];
}
mysqli_data_seek($result, 0);
?>

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employees Management</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');
        
        * {
            font-family: 'Poppins', sans-serif;
        }
        
        h1, h2, h3, h4, h5, h6 {
            font-family: 'Times New Roman', serif;
        }
        
        body {
            background: #f5f5f5;
        }
        
        .page-header {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            border-radius: 15px;
            padding: 25px 30px;
            margin-bottom: 30px;
            color: #fff;
        }
        
        .page-header h2 {
            margin: 0 0 8px 0;
            font-size: 28px;
            color: #fff;
        }
        
        .page-header p {
            margin: 0;
            opacity: 0.95;
            font-weight: 500;
        }
        
        .form-card, .table-card {
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .card-header-custom {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            padding: 15px 20px;
            color: #fff;
        }
        
        .card-header-custom h4 {
            margin: 0;
            font-size: 18px;
        }
        
        .card-header-custom i {
            margin-right: 10px;
        }
        
        .card-body-custom {
            padding: 25px;
        }
        
        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }
        
        .form-label i {
            color: #A04657;
            margin-right: 8px;
        }
        
        .form-control, .form-select {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 12px 15px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #A04657;
            box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
        }
        
        .btn-submit {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            color: #fff;
            border: none;
            padding: 12px 30px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
        }
        
        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(160,70,87,0.3);
            color: #fff;
        }
        
        .alert-custom {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 500;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }
        
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }
        
        .stat-card {
            background: #fff;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border-left: 4px solid #A04657;
        }
        
        .stat-value {
            font-size: 32px;
            font-weight: 700;
            color: #A04657;
        }
        
        .stat-label {
            color: #666;
            font-size: 14px;
            font-weight: 500;
            margin-top: 5px;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table th {
            background: #f8f9fa;
            font-weight: 700;
            color: #444;
            border-bottom: 2px solid #dee2e6;
        }
        
        .table td {
            vertical-align: middle;
            font-weight: 500;
        }
        
        .balance-positive {
            color: #28a745;
            font-weight: 700;
        }
        
        .btn-sm-custom {
            background: #A04657;
            color: #fff;
            padding: 5px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 600;
        }
        
        .btn-sm-custom:hover {
            background: #6b2a36;
            color: #fff;
        }
        
        .btn-detail {
            background: #17a2b8;
            margin-left: 5px;
        }
        
        .btn-detail:hover {
            background: #138496;
        }
        
        .required {
            color: #dc3545;
        }
        
        .info-text {
            font-size: 12px;
            color: #6c757d;
            margin-top: 5px;
        }
        
        @media (max-width: 768px) {
            .page-header {
                padding: 20px;
            }
            
            .page-header h2 {
                font-size: 22px;
            }
            
            .stat-value {
                font-size: 24px;
            }
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="page-header">
        <div>
            <h2><i class="fas fa-users"></i> Employees Management</h2>
            <p>Manage employee information, salaries, advances, and track balances</p>
        </div>
        <div>
            <i class="fas fa-user-tie" style="font-size: 48px; opacity: 0.5;"></i>
        </div>
    </div>
    
    <?php if($success_message): ?>
        <div class="alert-custom alert-success">
            <i class="fas fa-check-circle fa-lg"></i> <?php echo $success_message; ?>
        </div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger">
            <i class="fas fa-exclamation-triangle fa-lg"></i> <?php echo $error_message; ?>
        </div>
    <?php endif; ?>
    
    <div class="row">
        <div class="col-lg-5">
            <div class="form-card">
                <div class="card-header-custom">
                    <h4><i class="fas fa-plus-circle"></i> Add New Employee</h4>
                </div>
                <div class="card-body-custom">
                    <form method="POST" action="">
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-user"></i> Employee Name <span class="required">*</span></label>
                            <input type="text" name="employee_name" class="form-control" placeholder="Enter employee full name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-phone"></i> Phone Number <span class="required">*</span></label>
                            <input type="text" name="phone" class="form-control" placeholder="Enter phone number" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-briefcase"></i> Designation <span class="required">*</span></label>
                            <input type="text" name="designation" class="form-control" placeholder="e.g., Manager, Cashier, Attendant" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-money-bill-wave"></i> Basic Salary</label>
                            <div class="input-group">
                                <span class="input-group-text">Rs</span>
                                <input type="number" step="0.01" name="basic_salary" class="form-control" placeholder="0.00" value="0">
                            </div>
                            <div class="info-text">Monthly basic salary for this employee</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-chart-line"></i> Opening Balance</label>
                            <div class="row g-2">
                                <div class="col-8">
                                    <div class="input-group">
                                        <span class="input-group-text">Rs</span>
                                        <input type="number" step="0.01" name="opening_balance" class="form-control" placeholder="0.00" value="0">
                                    </div>
                                </div>
                                <div class="col-4">
                                    <select name="opening_balance_type" class="form-select">
                                        <option value="payable">Payable (Company owes)</option>
                                        <option value="receivable">Receivable (Employee owes)</option>
                                    </select>
                                </div>
                            </div>
                            <div class="info-text">
                                <i class="fas fa-info-circle"></i> 
                                <strong>Payable:</strong> Company has to pay employee | 
                                <strong>Receivable:</strong> Employee has taken advance
                            </div>
                        </div>
                        <button type="submit" name="add_employee" class="btn-submit">
                            <i class="fas fa-save"></i> Add Employee
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-7">
            <div class="table-card">
                <div class="card-header-custom">
                    <h4><i class="fas fa-list"></i> Employee List</h4>
                </div>
                <div class="card-body-custom">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo $total_employees; ?></div>
                                <div class="stat-label">Total Employees</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="stat-card">
                                <div class="stat-value">Rs <?php echo number_format($total_balance, 2); ?></div>
                                <div class="stat-label">Total Outstanding Payable</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Employee Name</th>
                                    <th>Phone</th>
                                    <th>Designation</th>
                                    <th>Basic Salary</th>
                                    <th>Balance</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(mysqli_num_rows($result) > 0): ?>
                                    <?php while($employee = mysqli_fetch_assoc($result)): ?>
                                        <tr>
                                            <td><?php echo $employee['id']; ?></div>
                                            <td>
                                                <strong><?php echo htmlspecialchars($employee['employee_name']); ?></strong>
                                            </div>
                                            <td><?php echo htmlspecialchars($employee['phone']); ?></div>
                                            <td><?php echo htmlspecialchars($employee['designation']); ?></div>
                                            <td>Rs <?php echo number_format($employee['basic_salary'], 2); ?></div>
                                            <td class="<?php echo $employee['balance'] > 0 ? 'balance-positive' : ''; ?>">
                                                Rs <?php echo number_format($employee['balance'], 2); ?>
                                            </div>
                                            <td>
                                                <a href="employee_detail.php?employee_id=<?php echo $employee['id']; ?>" class="btn-sm-custom btn-detail">
                                                    <i class="fas fa-eye"></i> Detail
                                                </a>
                                                <a href="employee_ledger.php?employee_id=<?php echo $employee['id']; ?>" class="btn-sm-custom">
                                                    <i class="fas fa-book"></i> Ledger
                                                </a>
                                            </div>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7" class="text-center py-5">
                                            <i class="fas fa-users" style="font-size: 48px; color: #ccc;"></i>
                                            <p class="mt-3 mb-0">No employees found</p>
                                            <small>Add your first employee using the form</small>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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