<?php
session_start();
require_once 'config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

$pdo = getDB();
$message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])) {
    try {
        $data = [
            'registration_no' => sanitize($_POST['registration_no']),
            'name' => sanitize($_POST['name']),
            'father_name' => sanitize($_POST['father_name']),
            'mother_name' => sanitize($_POST['mother_name']),
            'degree' => sanitize($_POST['degree']),
            'branch' => sanitize($_POST['branch']),
            'specialization' => sanitize($_POST['specialization']),
            'grade_point_average' => floatval($_POST['grade_point_average']),
            'total_grade_points' => floatval($_POST['total_grade_points']),
            'gender' => sanitize($_POST['gender']),
            'year_of_passing' => intval($_POST['year_of_passing']),
            'faculty' => sanitize($_POST['faculty']),
            'certificate_no' => generateCertificateNo()
        ];
        
        // Handle photo upload
        $photo_data = null;
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
            $photo_data = file_get_contents($_FILES['photo']['tmp_name']);
        }
        
        // Insert into database
        $sql = "INSERT INTO certificates (
            registration_no, name, father_name, mother_name, degree, branch, 
            specialization, grade_point_average, total_grade_points, gender, 
            photo, year_of_passing, faculty, certificate_no, generated_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $data['registration_no'],
            $data['name'],
            $data['father_name'],
            $data['mother_name'],
            $data['degree'],
            $data['branch'],
            $data['specialization'],
            $data['grade_point_average'],
            $data['total_grade_points'],
            $data['gender'],
            $photo_data,
            $data['year_of_passing'],
            $data['faculty'],
            $data['certificate_no'],
            $_SESSION['user_id']
        ]);
        
        $certificate_id = $pdo->lastInsertId();
        logActivity($certificate_id, 'created', $_SESSION['user_id']);
        
        $message = '<div class="success">Certificate created successfully! Certificate No: ' . $data['certificate_no'] . '</div>';
    } catch(PDOException $e) {
        if ($e->errorInfo[1] == 1062) {
            $message = '<div class="error">Registration number already exists!</div>';
        } else {
            $message = '<div class="error">Error: ' . $e->getMessage() . '</div>';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Certificate - SKUAST-K Portal</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f7fb; }
        .sidebar { width: 250px; background: #2d3748; color: white; height: 100vh; position: fixed; padding: 20px 0; }
        .sidebar h2 { padding: 0 20px 20px; border-bottom: 1px solid #4a5568; font-size: 18px; }
        .sidebar .user-info { padding: 20px; border-bottom: 1px solid #4a5568; margin-bottom: 20px; }
        .sidebar .user-info .name { font-weight: bold; font-size: 16px; }
        .sidebar .user-info .email { font-size: 12px; color: #a0aec0; }
        .sidebar a { display: block; padding: 12px 20px; color: #a0aec0; text-decoration: none; transition: all 0.3s; }
        .sidebar a:hover, .sidebar a.active { background: #4a5568; color: white; }
        .sidebar a i { width: 20px; margin-right: 10px; }
        .main-content { margin-left: 250px; padding: 30px; }
        .header { background: white; padding: 20px 30px; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); display: flex; justify-content: space-between; align-items: center; }
        .header h1 { font-size: 24px; color: #2d3748; }
        .form-container { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; color: #4a5568; font-weight: 500; font-size: 14px; }
        .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 5px; font-size: 14px; transition: border 0.3s; }
        .form-group input:focus, .form-group select:focus { outline: none; border-color: #667eea; }
        .btn { background: #667eea; color: white; border: none; padding: 12px 30px; border-radius: 5px; cursor: pointer; font-size: 16px; transition: background 0.3s; }
        .btn:hover { background: #5a67d8; }
        .btn-secondary { background: #718096; }
        .btn-secondary:hover { background: #4a5568; }
        .error { background: #fee; color: #c33; padding: 12px; border-radius: 5px; margin-bottom: 20px; }
        .success { background: #efe; color: #3c3; padding: 12px; border-radius: 5px; margin-bottom: 20px; }
        .full-width { grid-column: 1 / -1; }
    </style>
</head>
<body>
    <div class="sidebar">
        <h2>🎓 SKUAST-K Portal</h2>
        <div class="user-info">
            <div class="name"><?php echo htmlspecialchars($_SESSION['user_name']); ?></div>
            <div class="email"><?php echo htmlspecialchars($_SESSION['user_email']); ?></div>
        </div>
        <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
        <a href="add_certificate.php" class="active"><i class="fas fa-plus-circle"></i> Add Certificate</a>
        <a href="bulk_upload.php"><i class="fas fa-upload"></i> Bulk Upload</a>
        <a href="map_photo.php"><i class="fas fa-image"></i> Map Photo</a>
        <a href="generate_certificate.php"><i class="fas fa-file-pdf"></i> Generate Certificate</a>
        <a href="view_certificates.php"><i class="fas fa-list"></i> View All</a>
        <a href="logout.php" style="margin-top: 30px; border-top: 1px solid #4a5568; padding-top: 20px;"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
    
    <div class="main-content">
        <div class="header">
            <h1>Add New Certificate</h1>
            <a href="dashboard.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
        </div>
        
        <?php echo $message; ?>
        
        <div class="form-container">
            <form method="POST" action="" enctype="multipart/form-data">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Registration No *</label>
                        <input type="text" name="registration_no" placeholder="e.g., AG-2020-2283" required>
                    </div>
                    <div class="form-group">
                        <label>Certificate No (Auto-generated)</label>
                        <input type="text" value="<?php echo generateCertificateNo(); ?>" disabled style="background: #f7fafc;">
                    </div>
                    <div class="form-group">
                        <label>Student Name *</label>
                        <input type="text" name="name" placeholder="Full name" required>
                    </div>
                    <div class="form-group">
                        <label>Gender</label>
                        <select name="gender">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Father's Name *</label>
                        <input type="text" name="father_name" placeholder="Father's name" required>
                    </div>
                    <div class="form-group">
                        <label>Mother's Name *</label>
                        <input type="text" name="mother_name" placeholder="Mother's name" required>
                    </div>
                    <div class="form-group">
                        <label>Degree *</label>
                        <input type="text" name="degree" placeholder="e.g., B.Sc (Hons) Agriculture" required>
                    </div>
                    <div class="form-group">
                        <label>Branch</label>
                        <input type="text" name="branch" placeholder="Branch/Department">
                    </div>
                    <div class="form-group">
                        <label>Specialization</label>
                        <input type="text" name="specialization" placeholder="Specialization if any">
                    </div>
                    <div class="form-group">
                        <label>Faculty *</label>
                        <select name="faculty" required style="width: 100%; padding: 10px; border: 1px solid #e2e8f0; border-radius: 5px; font-size: 14px; background: white;">
                            <option value="">-- Select Faculty --</option>
                            <option value="Faculty of Agriculture">Faculty of Agriculture</option>
                            <option value="Faculty of Horticulture">Faculty of Horticulture</option>
                            <option value="Faculty of Forestry">Faculty of Forestry</option>
                            <option value="Faculty of Fisheries">Faculty of Fisheries</option>
                            <option value="Faculty of Veterinary Science and Animal Husbandry">Faculty of Veterinary Science and Animal Husbandry</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Grade Point Average *</label>
                        <input type="number" step="0.001" name="grade_point_average" placeholder="e.g., 7.640" required>
                    </div>
                    <div class="form-group">
                        <label>Total Grade Points</label>
                        <input type="number" step="0.01" name="total_grade_points" placeholder="Total grade points">
                    </div>
                    <div class="form-group">
                        <label>Year of Passing</label>
                        <select name="year_of_passing">
                            <?php for($i = date('Y'); $i >= 2000; $i--): ?>
                                <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Student Photo</label>
                        <input type="file" name="photo" accept="image/*">
                    </div>
                </div>
                <div style="margin-top: 20px;">
                    <button type="submit" name="submit" class="btn"><i class="fas fa-save"></i> Save Certificate</button>
                    <button type="reset" class="btn btn-secondary" style="margin-left: 10px;"><i class="fas fa-undo"></i> Reset</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>