<?php
// Check permission - only admins and managers can access
if(!isAdmin() && !isManager()) {
    echo "<div class='alert alert-danger'>Access Denied! Only Admins and Managers can access Intern Management.</div>";
    exit();
}

// Handle form submissions
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(isset($_POST['add_intern'])) {
        // Add new intern
        $full_name = $_POST['full_name'];
        $nic = $_POST['nic'];
        $contact = $_POST['contact'];
        $department = $_POST['department'];
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $supervisor_id = $_POST['supervisor_id'];
        $stipend = $_POST['stipend'];
        
        // First create user
        $username = strtolower(preg_replace('/[^a-zA-Z0-9]/', '.', $full_name));
        $password = password_hash('intern123', PASSWORD_DEFAULT);
        $email = $nic . '@intern.company.com';
        
        $stmt = $pdo->prepare("INSERT INTO users (username, password, email, role) VALUES (?, ?, ?, 'employee')");
        $stmt->execute([$username, $password, $email]);
        $user_id = $pdo->lastInsertId();
        
        // Create employee record
        $stmt = $pdo->prepare("INSERT INTO employees (user_id, full_name, nic_passport, contact_number, department, employment_type, join_date, salary) VALUES (?, ?, ?, ?, ?, 'intern', ?, ?)");
        $stmt->execute([$user_id, $full_name, $nic, $contact, $department, $start_date, $stipend]);
        $employee_id = $pdo->lastInsertId();
        
        // Create intern record
        $stmt = $pdo->prepare("INSERT INTO interns (employee_id, start_date, end_date, supervisor_id, status) VALUES (?, ?, ?, ?, 'active')");
        $stmt->execute([$employee_id, $start_date, $end_date, $supervisor_id]);
        
        echo "<div class='alert alert-success'>Intern added successfully! Default password: intern123</div>";
    }
    
    if(isset($_POST['update_intern'])) {
        $intern_id = $_POST['intern_id'];
        $training_checklist = $_POST['training_checklist'];
        $performance_review = $_POST['performance_review'];
        $status = $_POST['status'];
        $converted = isset($_POST['converted_to_permanent']) ? 1 : 0;
        
        $stmt = $pdo->prepare("UPDATE interns SET training_checklist = ?, performance_review = ?, status = ?, converted_to_permanent = ? WHERE id = ?");
        $stmt->execute([$training_checklist, $performance_review, $status, $converted, $intern_id]);
        
        // If converted to permanent, update employee type
        if($converted) {
            $stmt = $pdo->prepare("UPDATE employees e JOIN interns i ON e.id = i.employee_id SET e.employment_type = 'full-time' WHERE i.id = ?");
            $stmt->execute([$intern_id]);
        }
        
        echo "<div class='alert alert-success'>Intern details updated!</div>";
    }
}

// Handle convert to permanent action
if(isset($_GET['convert']) && is_numeric($_GET['convert'])) {
    $intern_id = $_GET['convert'];
    
    $stmt = $pdo->prepare("UPDATE interns SET converted_to_permanent = 1, status = 'completed' WHERE id = ?");
    $stmt->execute([$intern_id]);
    
    $stmt = $pdo->prepare("UPDATE employees e JOIN interns i ON e.id = i.employee_id SET e.employment_type = 'full-time' WHERE i.id = ?");
    $stmt->execute([$intern_id]);
    
    echo "<div class='alert alert-success'>Intern converted to permanent employee!</div>";
}

// Get all active employees for supervisor selection
$stmt = $pdo->query("SELECT id, full_name, department FROM employees WHERE employment_type IN ('full-time', 'part-time') ORDER BY full_name");
$supervisors = $stmt->fetchAll();

// Get all interns with details
$query = "SELECT i.*, e.full_name, e.contact_number, e.department, e.join_date, e.salary as stipend, 
          s.full_name as supervisor_name 
          FROM interns i 
          JOIN employees e ON i.employee_id = e.id 
          LEFT JOIN employees s ON i.supervisor_id = s.id 
          ORDER BY i.start_date DESC";
$stmt = $pdo->query($query);
$interns = $stmt->fetchAll();

// Get active interns count
$stmt = $pdo->query("SELECT COUNT(*) as count FROM interns WHERE status = 'active'");
$active_interns = $stmt->fetch()['count'];

// Get completed interns count
$stmt = $pdo->query("SELECT COUNT(*) as count FROM interns WHERE status = 'completed'");
$completed_interns = $stmt->fetch()['count'];

// Get converted interns count
$stmt = $pdo->query("SELECT COUNT(*) as count FROM interns WHERE converted_to_permanent = 1");
$converted_interns = $stmt->fetch()['count'];
?>

<div class="row mb-4">
    <div class="col-md-3">
        <div class="card border-primary">
            <div class="card-body">
                <h6 class="card-title">Active Interns</h6>
                <h2 class="text-primary"><?php echo $active_interns; ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-success">
            <div class="card-body">
                <h6 class="card-title">Completed</h6>
                <h2 class="text-success"><?php echo $completed_interns; ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-warning">
            <div class="card-body">
                <h6 class="card-title">Converted</h6>
                <h2 class="text-warning"><?php echo $converted_interns; ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-info">
            <div class="card-body">
                <h6 class="card-title">Total Interns</h6>
                <h2 class="text-info"><?php echo count($interns); ?></h2>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-4">
        <!-- Add New Intern Form -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Add New Intern</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label>Full Name</label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label>NIC/Passport Number</label>
                        <input type="text" name="nic" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label>Contact Number</label>
                        <input type="text" name="contact" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label>Department</label>
                        <select name="department" class="form-control" required>
                            <option value="">Select Department</option>
                            <option value="IT">IT Department</option>
                            <option value="HR">Human Resources</option>
                            <option value="Finance">Finance</option>
                            <option value="Marketing">Marketing</option>
                            <option value="Operations">Operations</option>
                            <option value="Sales">Sales</option>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Start Date</label>
                            <input type="date" name="start_date" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>End Date</label>
                            <input type="date" name="end_date" class="form-control" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label>Supervisor</label>
                        <select name="supervisor_id" class="form-control" required>
                            <option value="">Select Supervisor</option>
                            <?php foreach($supervisors as $supervisor): ?>
                            <option value="<?php echo $supervisor['id']; ?>">
                                <?php echo htmlspecialchars($supervisor['full_name']) . ' - ' . $supervisor['department']; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label>Monthly Stipend (Rs.)</label>
                        <input type="number" name="stipend" class="form-control" step="0.01" required>
                    </div>
                    <button type="submit" name="add_intern" class="btn btn-primary w-100">Add Intern</button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <!-- Interns List -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Interns List</h5>
                <div>
                    <button class="btn btn-sm btn-outline-secondary" onclick="printInterns()">
                        <i class="bi bi-printer"></i> Print
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Department</th>
                                <th>Duration</th>
                                <th>Supervisor</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($interns as $intern): ?>
                            <?php
                            $start = new DateTime($intern['start_date']);
                            $end = new DateTime($intern['end_date']);
                            $today = new DateTime();
                            $progress = 0;
                            
                            if($today < $start) {
                                $progress = 0;
                            } elseif($today > $end) {
                                $progress = 100;
                            } else {
                                $total_days = $end->diff($start)->days;
                                $days_passed = $today->diff($start)->days;
                                $progress = ($days_passed / $total_days) * 100;
                            }
                            
                            $status_color = '';
                            if($intern['status'] == 'active') $status_color = 'success';
                            elseif($intern['status'] == 'completed') $status_color = 'primary';
                            elseif($intern['status'] == 'terminated') $status_color = 'danger';
                            ?>
                            <tr>
                                <td>INT<?php echo str_pad($intern['id'], 3, '0', STR_PAD_LEFT); ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($intern['full_name']); ?></strong>
                                    <br><small class="text-muted"><?php echo $intern['contact_number']; ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($intern['department']); ?></td>
                                <td>
                                    <small><?php echo date('d M Y', strtotime($intern['start_date'])); ?> 
                                    to <?php echo date('d M Y', strtotime($intern['end_date'])); ?></small>
                                    <div class="progress" style="height: 5px;">
                                        <div class="progress-bar bg-<?php echo $progress >= 100 ? 'success' : 'info'; ?>" 
                                             style="width: <?php echo min($progress, 100); ?>%"></div>
                                    </div>
                                    <small><?php echo round($progress, 1); ?>% completed</small>
                                </td>
                                <td><?php echo $intern['supervisor_name'] ?? 'Not assigned'; ?></td>
                                <td>
                                    <span class="badge bg-<?php echo $status_color; ?>">
                                        <?php echo ucfirst($intern['status']); ?>
                                        <?php if($intern['converted_to_permanent']): ?>
                                        <i class="bi bi-check-circle"></i>
                                        <?php endif; ?>
                                    </span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" 
                                            data-bs-target="#viewInternModal<?php echo $intern['id']; ?>">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-warning" data-bs-toggle="modal" 
                                            data-bs-target="#editInternModal<?php echo $intern['id']; ?>">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <?php if($intern['status'] == 'active' && !$intern['converted_to_permanent']): ?>
                                    <a href="dashboard.php?page=interns&convert=<?php echo $intern['id']; ?>" 
                                       class="btn btn-sm btn-outline-success" 
                                       onclick="return confirm('Convert this intern to permanent employee?')">
                                        <i class="bi bi-person-check"></i>
                                    </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            
                            <!-- View Intern Modal -->
                            <div class="modal fade" id="viewInternModal<?php echo $intern['id']; ?>" tabindex="-1">
                                <div class="modal-dialog modal-lg">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Intern Details</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <p><strong>Name:</strong> <?php echo htmlspecialchars($intern['full_name']); ?></p>
                                                    <p><strong>Contact:</strong> <?php echo $intern['contact_number']; ?></p>
                                                    <p><strong>Department:</strong> <?php echo $intern['department']; ?></p>
                                                    <p><strong>Stipend:</strong> Rs. <?php echo number_format($intern['stipend'], 2); ?></p>
                                                </div>
                                                <div class="col-md-6">
                                                    <p><strong>Start Date:</strong> <?php echo date('d M Y', strtotime($intern['start_date'])); ?></p>
                                                    <p><strong>End Date:</strong> <?php echo date('d M Y', strtotime($intern['end_date'])); ?></p>
                                                    <p><strong>Supervisor:</strong> <?php echo $intern['supervisor_name'] ?? 'Not assigned'; ?></p>
                                                    <p><strong>Status:</strong> <span class="badge bg-<?php echo $status_color; ?>">
                                                        <?php echo ucfirst($intern['status']); ?>
                                                    </span></p>
                                                </div>
                                            </div>
                                            <hr>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <h6>Training Checklist</h6>
                                                    <div class="border p-3 rounded" style="min-height: 150px; max-height: 200px; overflow-y: auto;">
                                                        <?php echo nl2br(htmlspecialchars($intern['training_checklist'] ?? 'No checklist added.')); ?>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <h6>Performance Review</h6>
                                                    <div class="border p-3 rounded" style="min-height: 150px; max-height: 200px; overflow-y: auto;">
                                                        <?php echo nl2br(htmlspecialchars($intern['performance_review'] ?? 'No review added.')); ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Edit Intern Modal -->
                            <div class="modal fade" id="editInternModal<?php echo $intern['id']; ?>" tabindex="-1">
                                <div class="modal-dialog modal-lg">
                                    <div class="modal-content">
                                        <form method="POST">
                                            <div class="modal-header">
                                                <h5 class="modal-title">Edit Intern Details</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <input type="hidden" name="intern_id" value="<?php echo $intern['id']; ?>">
                                                
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label>Training Checklist</label>
                                                        <textarea name="training_checklist" class="form-control" rows="6" 
                                                                  placeholder="Enter training checklist items (one per line)"><?php echo htmlspecialchars($intern['training_checklist'] ?? ''); ?></textarea>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label>Performance Review</label>
                                                        <textarea name="performance_review" class="form-control" rows="6" 
                                                                  placeholder="Enter performance review"><?php echo htmlspecialchars($intern['performance_review'] ?? ''); ?></textarea>
                                                    </div>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label>Status</label>
                                                        <select name="status" class="form-control">
                                                            <option value="active" <?php echo $intern['status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                                                            <option value="completed" <?php echo $intern['status'] == 'completed' ? 'selected' : ''; ?>>Completed</option>
                                                            <option value="terminated" <?php echo $intern['status'] == 'terminated' ? 'selected' : ''; ?>>Terminated</option>
                                                        </select>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label class="d-block">&nbsp;</label>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" name="converted_to_permanent" 
                                                                   id="convert<?php echo $intern['id']; ?>" 
                                                                   value="1" <?php echo $intern['converted_to_permanent'] ? 'checked' : ''; ?>>
                                                            <label class="form-check-label" for="convert<?php echo $intern['id']; ?>">
                                                                Converted to Permanent
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                <button type="submit" name="update_intern" class="btn btn-primary">Save Changes</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Training Checklist Template -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="mb-0">Sample Training Checklist</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>IT Department Checklist:</h6>
                        <ul>
                            <li>Company orientation</li>
                            <li>Development tools setup</li>
                            <li>Code repository access</li>
                            <li>Project management tool training</li>
                            <li>Coding standards review</li>
                            <li>Testing procedures</li>
                            <li>Security protocols</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h6>HR Department Checklist:</h6>
                        <ul>
                            <li>HR policies review</li>
                            <li>Recruitment process</li>
                            <li>Employee onboarding</li>
                            <li>Leave management system</li>
                            <li>Performance evaluation process</li>
                            <li>Compliance training</li>
                            <li>Document management</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function printInterns() {
    window.print();
}
</script>