<?php
/**
 * Projects Management Page
 * Dozar & Tripper Management System
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';

$user = getCurrentUser();
$pdo = getPDO();
$error = '';
$success = '';
$duplicateWarning = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && hasRole('admin')) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $project_name = sanitize($_POST['project_name'] ?? '');
        $project_code = sanitize($_POST['project_code'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        
        // Check for duplicate
        $stmt = $pdo->prepare("SELECT id FROM projects WHERE project_name = ? AND is_active = 1");
        $stmt->execute([$project_name]);
        $duplicate = $stmt->fetch();
        
        if ($duplicate) {
            $duplicateWarning = 'Warning: A project with this name already exists!';
        } elseif ($project_name && $project_code) {
            $stmt = $pdo->prepare("INSERT INTO projects (project_name, project_code, description) VALUES (?, ?, ?)");
            $stmt->execute([$project_name, $project_code, $description]);
            $success = t('msg_save_success', 'Project added!');
            showMessage($success, 'success');
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'] ?? '';
        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM projects WHERE id=?");
            $stmt->execute([$id]);
            showMessage(t('msg_delete_success', 'Project deleted!'), 'success');
        }
    }
}

$projects = $pdo->query("SELECT * FROM projects ORDER BY project_name")->fetchAll();
?>
<?php include __DIR__ . '/../includes/header.php'; ?>

<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-map-marker-alt"></i> <?php echo t('nav_projects', 'Projects'); ?></h2>
            <?php if (hasRole('admin')): ?>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="fas fa-plus"></i> <?php echo t('action_add', 'Add Project'); ?>
            </button>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php displayMessage(); ?>

<?php if ($duplicateWarning): ?>
<div class="alert alert-warning">
    <i class="fas fa-exclamation-triangle"></i> <?php echo $duplicateWarning; ?>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Project Name</th>
                        <th>Code</th>
                        <th>Description</th>
                        <?php if (hasRole('admin')): ?>
                        <th>Actions</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($projects as $p): ?>
                    <tr>
                        <td><?php echo $p['project_name']; ?></td>
                        <td><?php echo $p['project_code']; ?></td>
                        <td><?php echo $p['description'] ?? '-'; ?></td>
                        <?php if (hasRole('admin')): ?>
                        <td>
                            <a href="view.php?id=<?php echo $p['id']; ?>" class="btn btn-sm btn-info">
                                <i class="fas fa-eye"></i>
                            </a>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?php echo $p['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Delete?')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if (hasRole('admin')): ?>
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Project</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">Project Name *</label>
                        <input type="text" name="project_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Code *</label>
                        <input type="text" name="project_code" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
