<?php
require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../includes/admin-functions.php';

// Provera da li je korisnik prijavljen kao admin
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Provera da li je prosleđen ID korisnika
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($user_id <= 0) {
    header('Location: /admin/users/');
    exit;
}

// Dohvatanje podataka o korisniku
$user = get_row("SELECT * FROM users WHERE id = ?", [$user_id]);

if (!$user) {
    $_SESSION['error_message'] = 'Korisnik nije pronađen.';
    header('Location: /admin/users/');
    exit;
}

// Obrada forme za ažuriranje korisnika
$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validacija obaveznih polja
    $required_fields = ['name', 'email'];
    
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = ucfirst($field) . ' je obavezno polje.';
        }
    }
    
    // Validacija email-a
    if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Email adresa nije validna.';
    }
    
    // Provera da li email već postoji (ako je promenjen)
    $email = trim($_POST['email']);
    if ($email !== $user['email']) {
        $email_exists = get_row("SELECT id FROM users WHERE email = ? AND id != ?", [$email, $user_id]);
        
        if ($email_exists) {
            $errors[] = 'Email adresa već postoji.';
        }
    }
    
    // Ako nema grešaka, ažuriraj korisnika
    if (empty($errors)) {
        $name = trim($_POST['name']);
        $phone = !empty($_POST['phone']) ? trim($_POST['phone']) : null;
        $address = !empty($_POST['address']) ? trim($_POST['address']) : null;
        $city = !empty($_POST['city']) ? trim($_POST['city']) : null;
        $zip = !empty($_POST['zip']) ? trim($_POST['zip']) : null;
        $role = !empty($_POST['role']) ? trim($_POST['role']) : 'customer';
        $status = !empty($_POST['status']) ? trim($_POST['status']) : 'active';
        
        // Obrada lozinke (samo ako je uneta nova)
        $password_change = false;
        if (!empty($_POST['password'])) {
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $password_change = true;
        }
        
        try {
            $conn->beginTransaction();
            
            // Ažuriranje korisnika
            if ($password_change) {
                $stmt = $conn->prepare("
                    UPDATE users SET 
                    name = ?, email = ?, password = ?, phone = ?, address = ?, 
                    city = ?, zip = ?, role = ?, status = ?, updated_at = NOW()
                    WHERE id = ?
                ");
                
                $stmt->execute([
                    $name, $email, $password, $phone, $address, 
                    $city, $zip, $role, $status, $user_id
                ]);
            } else {
                $stmt = $conn->prepare("
                    UPDATE users SET 
                    name = ?, email = ?, phone = ?, address = ?, 
                    city = ?, zip = ?, role = ?, status = ?, updated_at = NOW()
                    WHERE id = ?
                ");
                
                $stmt->execute([
                    $name, $email, $phone, $address, 
                    $city, $zip, $role, $status, $user_id
                ]);
            }
            
            $conn->commit();
            
            $success = 'Korisnik je uspešno ažuriran.';
            
            // Osvežavanje podataka o korisniku
            $user = get_row("SELECT * FROM users WHERE id = ?", [$user_id]);
            
        } catch (Exception $e) {
            $conn->rollBack();
            $errors[] = 'Došlo je do greške: ' . $e->getMessage();
        }
    }
}

// Naslov stranice
$page_title = 'Izmeni korisnika';

// Uključivanje header-a
require_once '../includes/header.php';
?>

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Izmeni korisnika</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/admin/">Kontrolna tabla</a></li>
                    <li class="breadcrumb-item"><a href="/admin/users/">Korisnici</a></li>
                    <li class="breadcrumb-item active">Izmeni korisnika</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<section class="content">
    <div class="container-fluid">
        <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $error): ?>
                <li><?php echo $error; ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
        
        <?php if (!empty($success)): ?>
        <div class="alert alert-success">
            <?php echo $success; ?>
        </div>
        <?php endif; ?>
        
        <form action="" method="post">
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Osnovni podaci</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="name">Ime i prezime <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name" name="name" required value="<?php echo htmlspecialchars($user['name']); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="email">Email <span class="text-danger">*</span></label>
                                <input type="email" class="form-control" id="email" name="email" required value="<?php echo htmlspecialchars($user['email']); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="password">Lozinka</label>
                                <input type="password" class="form-control" id="password" name="password" autocomplete="new-password">
                                <small class="form-text text-muted">Ostavite prazno da zadržite trenutnu lozinku.</small>
                            </div>
                            
                            <div class="form-group">
                                <label for="phone">Telefon</label>
                                <input type="text" class="form-control" id="phone" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Adresa i status</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="address">Adresa</label>
                                <input type="text" class="form-control" id="address" name="address" value="<?php echo htmlspecialchars($user['address'] ?? ''); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="city">Grad</label>
                                <input type="text" class="form-control" id="city" name="city" value="<?php echo htmlspecialchars($user['city'] ?? ''); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="zip">Poštanski broj</label>
                                <input type="text" class="form-control" id="zip" name="zip" value="<?php echo htmlspecialchars($user['zip'] ?? ''); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="role">Uloga</label>
                                <select class="form-control" id="role" name="role">
                                    <option value="customer" <?php echo $user['role'] === 'customer' ? 'selected' : ''; ?>>Kupac</option>
                                    <option value="admin" <?php echo $user['role'] === 'admin' ? 'selected' : ''; ?>>Administrator</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="status">Status</label>
                                <select class="form-control" id="status" name="status">
                                    <option value="active" <?php echo $user['status'] === 'active' ? 'selected' : ''; ?>>Aktivan</option>
                                    <option value="inactive" <?php echo $user['status'] === 'inactive' ? 'selected' : ''; ?>>Neaktivan</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <div class="form-group">
                                <button type="submit" class="btn btn-primary">Sačuvaj izmene</button>
                                <a href="/admin/users/" class="btn btn-default ml-2">Odustani</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>

<?php require_once '../includes/footer.php'; ?>