<?php

    $submit = getuserdata('submit');
    $actiune = getuserdata('actiune');
    $id = getuserdata('id', 0);
    $imagine = getuserdata('imagine', '');
    $descriere = getuserdata('descriere', '');
    $id_categorie = getuserdata('id_categorie', 0);
    $categorie = getuserdata('categorie', '');
    
    function imageresize($image, $maxwidth, $maxheight)
    {
        $w = imagesx($image);
        $h = imagesy($image);
        $procw = (float)$maxwidth / (float)$w;
        $proch = (float)$maxheight / (float)$h;
        $proc = min(array($procw, $proch));
        if ($proc > 1) $proc = 1;
        $new_width = (int)($w * $proc);
        $new_height = (int)($h * $proc);
        $new_image = imagecreatetruecolor($new_width, $new_height);
        imagealphablending($new_image, false);
        imagesavealpha($new_image, true);
        $transparent_colors = imagecolorsforindex($image, $transparent_index);
        $transparent_index = imagecolorallocatealpha($new_image, $transparent_colors['red'], $transparent_colors['green'], 
                                                     $transparent_colors['blue'], $transparent_colors['alpha']);
        imagefill($new_image, 0, 0, $transparent_index);
        imagecopyresampled($new_image, $image, $bordersizeh, $bordersizev, 0, 0, $new_width, $new_height, $w, $h);
        return $new_image;
    }
    
    switch ($actiune)
    {
        case 'do_editare_categorie':
            if ($submit != 'Salvează')
            {
                header("Location: {$_SERVER['PHP_SELF']}?pagina=$pagina");
                exit;
            }
            if ($categorie != "")
            {
                $q = mysql_query("SELECT * FROM imagini_categorii WHERE id = $id_categorie");
                if ($r = mysql_fetch_assoc($q))
                {
                    mysql_query("UPDATE imagini_categorii SET categorie = '$categorie' WHERE id = $id_categorie");
                    $eroare = mysql_error();
                }
                else
                {
                    $qm = mysql_query("SELECT MAX(nr_crt) AS nr FROM imagini_categorii");
                    if ($rm = mysql_fetch_assoc($qm)) $nrcrt = ((int)$rm['nr']) + 1;
                                                 else $nrcrt = 1; 
                    mysql_query("INSERT INTO imagini_categorii (categorie, nr_crt) VALUES ('$categorie', $nrcrt)");
                    $id = mysql_insert_id();
                    $eroare = mysql_error();
                }
            }
            else $eroare = 'Nu ați introdus numele categoriei';
            if (!$eroare)
            {
                header("Location: {$_SERVER['PHP_SELF']}?pagina=$pagina");
                exit;
            }
        case 'editare_categorie':
            writepagetitle();
            writepagetop();
            writeinfolayer();
            $q = mysql_query("SELECT * FROM imagini_categorii WHERE id = $id_categorie");
            if ($r = mysql_fetch_assoc($q))
            {
                $categorie = $r['categorie'];
            }
            echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
            echo "<input type='hidden' name='actiune' value='do_editare_categorie'>";
            echo "<input type='hidden' name='pagina' value='$pagina'>";
            echo "<input type='hidden' name='id_categorie' value='{$r['id']}'>";
            echo "<center><table class='formular'>";
            echo "<tr><th>Categorie:</th><td><input type='text' name='categorie' value='$categorie'></td></tr>";
            echo "<tr><td>&nbsp;</td><td class='butoane'>";
            echo "<input type='submit' name='submit' id='save' value='Salvează' class='buton_salveaza'>";
            echo "<input type='submit' name='submit' id='cancel' value='Anulează' class='buton_anuleaza'>";
            echo "</td></tr></table></center></form>";
            writepagebottom();
            exit;
        case 'do_stergere_categorie':
            if ($submit != 'Șterge')
            {
                header("Location: {$_SERVER['PHP_SELF']}");
                exit;
            }
            $q = mysql_query("SELECT * FROM imagini_categorii WHERE id = $id_categorie");
            if ($r = mysql_fetch_assoc($q))
            {
                $qi = mysql_query("SELECT * FROM imagini WHERE id_categorie = $id_categorie");
                while ($ri = mysql_fetch_assoc($qi))
                {
                    if ($ri['imagine']) unlink($imagespath.'capturi/'.$ri['imagine']);
                }
                mysql_query("DELETE FROM imagini WHERE id_categorie = $id_categorie");
                mysql_query("DELETE FROM imagini_categorii WHERE id = $id_categorie");
                mysql_query("UPDATE imagini_categorii SET nr_crt = nr_crt - 1 WHERE nr_crt > {$r['nr_crt']}");
                $eroare = mysql_error();
            }
            else
            {
                $eroare = 'Categoria selectată nu poate fi accesată';
            }
            if (!$eroare)
            {
                header("Location: {$_SERVER['PHP_SELF']}?pagina=$pagina");
                exit;
            }
        case 'stergere_categorie':
            $q = mysql_query("SELECT * FROM imagini_categorii WHERE id = $id_categorie");
            if ($r = mysql_fetch_assoc($q))
            {
                writepagetitle();
                writepagetop();
                writeinfolayer();
                $categorie = $r['categorie'];
                echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
                echo "<input type='hidden' name='actiune' value='do_stergere_categorie'>";
                echo "<input type='hidden' name='pagina' value='$pagina'>";
                echo "<input type='hidden' name='id_categorie' value='{$r['id']}'>";
                echo "<center><table class='formular'>";
                echo "<tr><th>Sigur doriți să ștergeți categoria '$categorie'?</th></tr>";
                echo "<tr><td class='butoane'>";
                echo "<input type='submit' name='submit' id='save' value='Șterge'>";
                echo "<input type='submit' name='submit' id='cancel' value='Anulează'>";
                echo "</td></tr></table></center></form>";
                writepagebottom();
                exit;
            }
        case 'do_down_categorie':
            $q = mysql_query("SELECT * FROM imagini_categorii WHERE id = $id_categorie");
            if ($r = mysql_fetch_assoc($q))
            {
                $q1 = mysql_query("SELECT * FROM imagini_categorii WHERE nr_crt > {$r['nr_crt']} ORDER BY nr_crt ASC LIMIT 0, 1");
                if ($r1 = mysql_fetch_assoc($q1))
                {
                    mysql_query("UPDATE imagini_categorii SET nr_crt = {$r['nr_crt']} WHERE id = {$r1['id']}");
                    mysql_query("UPDATE imagini_categorii SET nr_crt = {$r1['nr_crt']} WHERE id = {$r['id']}");
                }
            }
            break;
        case 'do_up_categorie':
            $q = mysql_query("SELECT * FROM imagini_categorii WHERE id = $id_categorie");
            if ($r = mysql_fetch_assoc($q))
            {
                $q1 = mysql_query("SELECT * FROM imagini_categorii WHERE nr_crt < {$r['nr_crt']} ORDER BY nr_crt DESC LIMIT 0, 1");
                if ($r1 = mysql_fetch_assoc($q1))
                {
                    mysql_query("UPDATE imagini_categorii SET nr_crt = {$r['nr_crt']} WHERE id = {$r1['id']}");
                    mysql_query("UPDATE imagini_categorii SET nr_crt = {$r1['nr_crt']} WHERE id = {$r['id']}");
                }
            }
            break;


        case 'do_editare':
            if ($submit != 'Salvează')
            {
                header("Location: {$_SERVER['PHP_SELF']}?pagina=$pagina");
                exit;
            }
            if (isset($_FILES['imagine']))
            {
                $q = mysql_query("SELECT * FROM imagini WHERE id = $id");
                if ($r = mysql_fetch_assoc($q))
                {
                    mysql_query("UPDATE imagini SET descriere = '$descriere' WHERE id = $id");
                    $eroare = mysql_error();
                }
                else
                {
                    $qm = mysql_query("SELECT MAX(nr_crt) AS nr FROM imagini WHERE id_categorie = $id_categorie");
                    if ($rm = mysql_fetch_assoc($qm)) $nrcrt = ((int)$rm['nr']) + 1;
                                                 else $nrcrt = 1; 
                    mysql_query("INSERT INTO imagini (descriere, nr_crt, id_categorie) VALUES ('$descriere', $nrcrt, $id_categorie)");
                    $id = mysql_insert_id();
                    $eroare = mysql_error();
                }
                // Incarc si fisierul
                if (!$eroare)
                {
                    if ($_FILES['imagine']['error'] == UPLOAD_ERR_OK)
                    {
                        $filename = $_FILES['imagine']['name'];
                        $i = 0;
                        while (file_exists($imagespath.'capturi/'.$filename))
                        {
                            $extpos = strrpos($filename, '.');
                            $filename = substr($filename, 0, $extpos).(++$i).strrchr($filename, '.');
                        }
                        move_uploaded_file($_FILES['imagine']['tmp_name'], $imagespath.'capturi/'.$filename);
                        list($w, $h) = getimagesize($imagespath.'capturi/'.$filename);
                        $info = getimagesize($imagespath.'capturi/'.$filename);
                        switch ($info[2])
                        {
                            case IMAGETYPE_GIF:
                                $sourcelayer = imagecreatefromgif($imagespath.'capturi/'.$filename);
                                $dest = imageresize($sourcelayer, 800, 600);
                                imagegif($dest, $imagespath.'capturi/'.$filename);
                                break;
                            case IMAGETYPE_JPEG:
                                $sourcelayer = imagecreatefromjpeg($imagespath.'capturi/'.$filename);
                                $dest = imageresize($sourcelayer, 800, 600);
                                imagejpeg($dest, $imagespath.'capturi/'.$filename);
                                break;
                            case IMAGETYPE_PNG:
                                $sourcelayer = imagecreatefrompng($imagespath.'capturi/'.$filename);
                                $dest = imageresize($sourcelayer, 800, 600);
                                imagepng($dest, $imagespath.'capturi/'.$filename);
                                break;
                            case IMAGETYPE_WBMP:
                                $sourcelayer = imagecreatefromwbmp($imagespath.'capturi/'.$filename);
                                $dest = imageresize($sourcelayer, 800, 600);
                                imagewbmp($dest, $imagespath.'capturi/'.$filename);
                                break;
                            case IMAGETYPE_XBM:
                                $sourcelayer = imagecreatefromxbm($imagespath.'capturi/'.$filename);
                                $dest = imageresize($sourcelayer, 800, 600);
                                imagexbm($dest, $imagespath.'capturi/'.$filename);
                                break;
                            default:
                                $eroare = "Acest tip de fișier nu este suportat.";
                                $filename = '';
                                exit;
                        }
                        if ($filename) mysql_query("UPDATE imagini SET imagine = '$filename' WHERE id = $id");
                    }
                    else $eroare = 'Fișierul nu a putut fi încărcat pe server!';
                }    
            }
            else $eroare = 'Nu ați ales nicio imagine pentru a fi încărcată';
            if (!$eroare)
            {
                header("Location: {$_SERVER['PHP_SELF']}?pagina=$pagina");
                exit;
            }
        case 'editare':
            writepagetitle();
            writepagetop();
            writeinfolayer();
            $q = mysql_query("SELECT * FROM imagini WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                $id_categorie = $r['id_categorie'];
                $imagine = $r['imagine'];
                $descriere = $r['descriere'];
            }
            echo "<form action='{$_SERVER['PHP_SELF']}' method='POST' enctype='multipart/form-data'>";
            echo "<input type='hidden' name='actiune' value='do_editare'>";
            echo "<input type='hidden' name='pagina' value='$pagina'>";
            echo "<input type='hidden' name='id' value='{$r['id']}'>";
            echo "<input type='hidden' name='id_categorie' value='$id_categorie'>";
            echo "<center><table class='formular'>";
            echo "<tr><th>Descriere:</th><td><input type='text' name='descriere' value='$descriere'></td></tr>";
            echo "<tr><th>Poza:</th><td><input type='file' name='imagine'></td></tr>";
            echo "<tr><td>&nbsp;</td><td class='butoane'>";
            echo "<input type='submit' name='submit' id='save' value='Salvează' class='buton_salveaza'>";
            echo "<input type='submit' name='submit' id='cancel' value='Anulează' class='buton_anuleaza'>";
            echo "</td></tr></table></center></form>";
            writepagebottom();
            exit;
        case 'do_stergere':
            if ($submit != 'Șterge')
            {
                header("Location: {$_SERVER['PHP_SELF']}");
                exit;
            }
            $q = mysql_query("SELECT * FROM imagini WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                if ($r['imagine']) unlink($imagespath.'capturi/'.$r['imagine']);
                mysql_query("UPDATE imagini SET nr_crt = nr_crt - 1 WHERE nr_crt > {$r['nr_crt']} AND id_categorie = $id_categorie");
                mysql_query("DELETE FROM imagini WHERE id = $id");
                $eroare = mysql_error();
            }
            else
            {
                $eroare = 'Imaginea selectată nu poate fi accesată';
            }
            if (!$eroare)
            {
                header("Location: {$_SERVER['PHP_SELF']}?pagina=$pagina");
                exit;
            }
        case 'stergere':
            $q = mysql_query("SELECT * FROM imagini WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                writepagetitle();
                writepagetop();
                writeinfolayer();
                $descriere = $r['descriere'];
                $id_categorie = $r['id_categorie'];
                echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
                echo "<input type='hidden' name='actiune' value='do_stergere'>";
                echo "<input type='hidden' name='pagina' value='$pagina'>";
                echo "<input type='hidden' name='id' value='{$r['id']}'>";
                echo "<input type='hidden' name='id_categorie' value='{$r['id_categorie']}'>";
                echo "<center><table class='formular'>";
                echo "<tr><th>Sigur doriți să ștergeți imaginea '$descriere'?</th></tr>";
                echo "<tr><td class='butoane'>";
                echo "<input type='submit' name='submit' id='save' value='Șterge'>";
                echo "<input type='submit' name='submit' id='cancel' value='Anulează'>";
                echo "</td></tr></table></center></form>";
                writepagebottom();
                exit;
            }
        case 'do_down':
            $q = mysql_query("SELECT * FROM imagini WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                $q1 = mysql_query("SELECT * FROM imagini WHERE nr_crt > {$r['nr_crt']} AND id_categorie = {$r['id_categorie']} ORDER BY nr_crt ASC LIMIT 0, 1");
                if ($r1 = mysql_fetch_assoc($q1))
                {
                    mysql_query("UPDATE imagini SET nr_crt = {$r['nr_crt']} WHERE id = {$r1['id']}");
                    mysql_query("UPDATE imagini SET nr_crt = {$r1['nr_crt']} WHERE id = {$r['id']}");
                }
            }
            break;
        case 'do_up':
            $q = mysql_query("SELECT * FROM imagini WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                $q1 = mysql_query("SELECT * FROM imagini WHERE nr_crt < {$r['nr_crt']} AND id_categorie = {$r['id_categorie']} ORDER BY nr_crt DESC LIMIT 0, 1");
                if ($r1 = mysql_fetch_assoc($q1))
                {
                    mysql_query("UPDATE imagini SET nr_crt = {$r['nr_crt']} WHERE id = {$r1['id']}");
                    mysql_query("UPDATE imagini SET nr_crt = {$r1['nr_crt']} WHERE id = {$r['id']}");
                }
            }
            break;
    }

    writepagetitle();
    writepagetop();
    writeinfolayer();
    echo "<span class='articol'>";
    echo "<h1>Capturi de ecran</h1>";
    $qc = mysql_query("SELECT * FROM imagini_categorii ORDER BY nr_crt ASC");
    while ($rc = mysql_fetch_assoc($qc))
    {
        echo "<table><tr><th style='width: 500px'>{$rc['categorie']}</th><th class='butoane'>";
        echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
        echo "<input type='hidden' name='actiune' value='editare_categorie'>";
        echo "<input type='hidden' name='pagina' value='$pagina'>";
        echo "<input type='hidden' name='id_categorie' value='{$rc['id']}'>";
        echo "<input type='submit' name='submit' id='edit' value='Editează'>";
        echo "</form>";
        echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
        echo "<input type='hidden' name='actiune' value='stergere_categorie'>";
        echo "<input type='hidden' name='pagina' value='$pagina'>";
        echo "<input type='hidden' name='id_categorie' value='{$rc['id']}'>";
        echo "<input type='submit' name='submit' id='delete' value='Șterge'>";
        echo "</form></th></tr>";
        $q = mysql_query("SELECT * FROM imagini WHERE id_categorie = {$rc['id']} ORDER BY nr_crt ASC");
        while ($r = mysql_fetch_assoc($q))
        {
            echo "<tr><td>{$r['descriere']}</td>";
            echo "<td class='butoane'>";
            echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
            echo "<input type='hidden' name='actiune' value='editare'>";
            echo "<input type='hidden' name='pagina' value='$pagina'>";
            echo "<input type='hidden' name='id' value='{$r['id']}'>";
            echo "<input type='hidden' name='id_categorie' value='{$r['id_categorie']}'>";
            echo "<input type='submit' name='submit' id='edit' value='Editează'>";
            echo "</form>";
            echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
            echo "<input type='hidden' name='actiune' value='stergere'>";
            echo "<input type='hidden' name='pagina' value='$pagina'>";
            echo "<input type='hidden' name='id' value='{$r['id']}'>";
            echo "<input type='hidden' name='id_categorie' value='{$r['id_categorie']}'>";
            echo "<input type='submit' name='submit' id='delete' value='Șterge'>";
            echo "</form>";
            echo "<a href='{$_SERVER['PHP_SELF']}?pagina=$pagina&actiune=do_up&id={$r['id']}' ".
                 "style='padding: 3px 2px' title='sus'><img src='{$imagesroot}btnimg_up.png' alt='sus'></a>";
            echo "<a href='{$_SERVER['PHP_SELF']}?pagina=$pagina&actiune=do_down&id={$r['id']}' ".
                 "style='padding: 3px 2px' title='jos'><img src='{$imagesroot}btnimg_down.png' alt='jos'></a>";
            echo "</td></tr>";
        }
        echo "</table>";
        echo "<form action='{$_SERVER['PHP_SELF']}' method='POST' class='butoane'>";
        echo "<input type='hidden' name='actiune' value='editare'>";
        echo "<input type='hidden' name='pagina' value='$pagina'>";
        echo "<input type='hidden' name='id' value='0'>";
        echo "<input type='hidden' name='id_categorie' value='{$rc['id']}'>";
        echo "<input type='submit' name='submit' id='add' style='width: 200px' value='Adaugă imagine'>";
        echo "</form>";    
    }
    echo "<form action='{$_SERVER['PHP_SELF']}' method='POST' class='butoane'>";
    echo "<input type='hidden' name='actiune' value='editare_categorie'>";
    echo "<input type='hidden' name='pagina' value='$pagina'>";
    echo "<input type='hidden' name='id' value='0'>";
    echo "<input type='hidden' name='id_categorie' value='0'>";
    echo "<input type='submit' name='submit' id='add' style='width: 200px' value='Adaugă categorie'>";
    echo "</form></span>";    
    writepagebottom();
?>